Setting up a local web server with Python

Cover Image

Hey there, Linux enthusiasts! Ever wanted to quickly serve up a simple website, share a file, or test some web code locally without the hassle of a full-blown web server setup like Apache or Nginx? Well, Python has your back! It comes with a built-in web server module that's super easy to use. Let's dive in!

Why Use Python's Built-in Server?

Think of Python's simple server as a Swiss Army knife for quick web tasks. It's perfect for:

  • Testing your HTML, CSS, and JavaScript files locally.
  • Sharing files over your local network.
  • Experimenting with basic web development concepts.

It's not designed for production use (it's not built for high traffic or security), but for quick and dirty web serving, it's a lifesaver.

Setting Up Your Server (The Easy Way!)

Ready to get started? It's incredibly simple. Open your terminal and navigate to the directory you want to serve. For example, if your website files are in a folder called "mywebsite", you would type:

cd mywebsite

Now, depending on your Python version, the command will be slightly different:

  • Python 2: python -m SimpleHTTPServer 8000
  • Python 3: python3 -m http.server 8000

The 8000 part specifies the port number. You can choose a different port if you prefer (like 8080 or 8888), but make sure it's not already in use. If you leave the port blank, Python 3 will often default to port 8000, while Python 2 will throw an error.

Accessing Your Website

Once the server is running, open your web browser and type the following address:

http://localhost:8000

Replace 8000 with the port number you used in the previous step if you chose a different one. If you're accessing the server from another computer on your local network, use the server computer's IP address instead of localhost:

http://[Server's IP Address]:8000

For example:

http://192.168.1.10:8000

Stopping the Server

To stop the server, simply press Ctrl+C in the terminal window where the server is running.

A Few Extra Tips

  • Serving a specific file: If you want to serve a specific file as the default page (e.g., index.html), just make sure it's in the directory you're serving. The server will automatically serve it when you access the root URL (http://localhost:8000).
  • File Permissions: Make sure the files you're trying to serve have the correct read permissions for the user running the Python command. If you're getting errors, check your file permissions.
  • Port Already in Use: If you get an error that the port is already in use, try using a different port number. Commonly used ports include 8000, 8080, and 8888.

That's it! A quick and easy way to spin up a local web server with Python. Happy coding!