In this article, I'll show you simple and beginner-friendly steps to set up Apache with the Python WSGI module on Ubuntu 24.04, Ubuntu 23.04, and other previous versions for deploying Python web applications on Apache web servers.

Step 1: Install Required Packages

First, update the system package list and outdated packages using this command:

$ sudo apt update && sudo apt upgrade

Next, you need to install the Apache web server and Python package (if you already have them installed, you can skip this step).

$ sudo apt install apache2 python3

Once done, install the Python WSGI module for Apache using this command:

$ sudo apt install libapache2-mod-wsgi-py3

Step 2: Create a Python Application

To verify the integration of the Python WSGI module with Apache, we will create a simple Python application that can later be accessed from a browser. Thus, start by creating a separate directory for storing your Python application and moving into it.

$ sudo mkdir /var/www/html/myapp && cd /var/www/html/myapp

Inside the directory, create a Python file named wsgi.py with the following content:

def application(environ, start_response):
status = '200 OK'
output = b'Hello from Ubuntu Shell!'

response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [output]

Save and close the file when finished.

Step 3: Configure Apache to Serve Your Python App

Now that we've installed the required packages and modules and created our Python application, it's time to create an Apache virtual host configuration file to serve the Python app via HTTP. To do this, use this command to create a new Apache configuration file:

$ sudo nano /etc/apache2/conf-available/python-wsgi.conf

Add the following line:

WSGIScriptAlias /wsgi /var/www/html/myapp/wsgi.py

Save and close the file, then activate the newly created Apache virtual host configuration file using this command:

$ sudo a2enconf python-wsgi

Finally, restart the Apache service to apply the changes.

$ sudo systemctl restart apache2

Step 4: Test Your Application

Now, open your browser and access the Apache web server with the Python application via your IP address (like this "http://ip-address/wsgi"), and you will be redirected to the following screen.

accessing Python application on browser

Wrap Up

Congratulations! You have successfully configured Apache to serve your Python application. A common problem that users often experience is that Apache isn't loading; a primary reason for this could be that another server, such as Nginx, is already running on port 80. You can resolve this issue after identifying it, but if the problem persists, let us know in the comments.