DEV Community

Cover image for Starting an HTTP Server in Seconds With Just 2 Lines of Code
Ben Soyka
Ben Soyka

Posted on • Originally published at Medium

Starting an HTTP Server in Seconds With Just 2 Lines of Code

When I’m developing a website on my PC, I like to be able to test out the design on multiple devices — occasionally sharing it live with people around the world.

Recently, I developed a simple batch script to do two things: start an HTTP server and open up a tunnel to the server so anyone on the internet can access it.


Prerequisites

There are a few things you’ll need to have set up before starting your HTTP server:

Windows PC

The main code in this article is made in a DOS batch (.bat) file, which is only available on PCs.

Python 2 or 3

Python will be used to start the server on your localhost. You can use either Python 2.x or Python 3.x. You’ll also need to make sure it’s added to your PATH when you install it.

There’s only a minor change you’ll need to make to the code if you choose to use a version of Python 2.

ngrok

To open up a tunnel to your local machine from the rest of the web, we’ll use ngrok. It’s free and fairly easy to install and use, but make sure you add it to your PATH as well.


The code

To help us understand what’s going on here, we’ll take a look at each line of the code.

Starting the server

As mentioned earlier, we’ll use Python to start up a local HTTP server.

The code above starts a new command prompt window running Python’s http.server module on port 80. This means the contents of the folder you run this command in will now be served at http://localhost:80.

If you’re using a version of Python 2, all you need to do is replace http.server with SimpleHTTPServer.

Opening a tunnel to localhost

We’ll use ngrok to open up a tunnel to the server running on your localhost. This means anyone who visits your auto-generated ngrok URL will see your local server running on Python.


Setting it all up

To use this script, you’ll want to save it to a folder in the PATH variable. This means you’ll be able to use it from anywhere on your computer.

To actually use the script, click on the address bar in the File Explorer, type in the name of the script as you saved it — with or without the file extension — and press Enter.

Alternatively, you can open a Command Prompt window, navigate to the folder you’d like to host, and run the script from there.


This simple script can make your life a whole lot easier when it comes to developing a website. With just a few clicks, you can start a server and see how your site looks on a variety of devices.

Top comments (0)