Setting up a local web server with Python
Super Simple Local Web Server with Python: Your Linux Quick Start Guide
Want to quickly share files from your Linux machine, test a basic website, or just play around with web development? Python has you covered! Believe it or not, setting up a local web server is ridiculously easy, and you don't need to be a Python guru to do it.
This guide shows you how to launch a basic HTTP server using Python in just a few commands. Let's dive in!
Step 1: Make Sure Python is Installed
Most Linux distributions come with Python pre-installed. To check if you have it, open your terminal and type:
python3 --version
If you see a version number (like "Python 3.9.7"), you're good to go! If not, you'll need to install Python. The process varies depending on your distro. For Debian/Ubuntu based systems:
sudo apt update
sudo apt install python3
Step 2: Navigate to Your Files
Use the cd command to navigate to the directory containing the files you want to serve. For example, if your files are in a directory called "mywebsite" in your home directory:
cd ~/mywebsite
Make sure this directory contains at least one HTML file, such as index.html. You can create a simple one like this:
echo "<h1>Hello from my local server!</h1>" > index.html
Step 3: Launch the Web Server
This is the magic command! In your terminal, within the directory containing your files, type:
python3 -m http.server
This command starts a simple HTTP server on port 8000. You should see output similar to this:
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
You can specify a different port if 8000 is already in use. For example, to use port 8080:
python3 -m http.server 8080
Step 4: Access Your Web Server
Open your web browser and go to http://localhost:8000 (or http://localhost:8080 if you used port 8080). You should see the contents of the directory you're serving. If you created the index.html file as shown above, you will see "Hello from my local server!" displayed in your browser.
Important Notes:
- This is a very basic server meant for development and testing. It's not suitable for production environments.
- To stop the server, press
Ctrl+Cin your terminal. - Files are served directly from the directory you launched the server from.
- If you put an
index.htmlfile in the served directory, it will be automatically displayed as the home page.
Next Steps:
Now that you have a basic server running, you can explore these possibilities:
- Experiment with creating more complex HTML pages.
- Add CSS and JavaScript files to your directory and see how the server serves them.
- Learn about more advanced web frameworks like Flask or Django for building real web applications.
Have fun playing around with your local web server!