Skip to main content

Running a Simple Web Server with Python

· 2 min read
John Crickett
Code Challenge Writer

Out of the box Python comes with a simple Web Server. It’s not suitable for production, but it’s very useful for testing and development.

Here’s a quick guide to setting up and using it with Python 3.

Step 0 - Check If You Need To Install Python 3

From a command line run:

% python --version
Python 3.11.2

If you see a version, proceed to Step 2, otherwise, Step 1.

Step 1 - Install Python 3

The are full instructions on installing Python for your OS in Python’s Beginners Guide / Downloading Python.

Step 2 - Create Some Files To Server

By default Python’s built in HTTP Server will serve the files from it’s current directory, so create a directory and add a file for it to server. I usually do it this way:

% mkdir www && cd www
% touch index.html

Then I add some simple content to the page, i.e.:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Index Page</title>
</head>
<body>
Hello from the web server running at: <script>document.write(window.location.host);</script>
</body>
</html>

Step 3 - Run The Server

You can now run your server as so:

% python -m http.server
Serving HTTP on :: port 8000 (http://[::]:8000/) ...

The point your browser to http://localhost:8000 to see the result.

You can create multiple servers serving different folders and listening on different ports by changing the command line used to start the server:

% python -m http.server 80 --directory server
Serving HTTP on :: port 80 (http://[::]:80/) ...

You can find more options in the Python http.server module documentation.