How To Install mod_wsgi on Ubuntu

Last updated on January 7th, 2023 at 05:02 am

mod_wsgi allows you to run python applications in Apache web server. So it can be used to run python-based websites in Apache. Here’s how to install mod_wsgi on Ubuntu / Debian systems.

How To Install mod_wsgi on Ubuntu

Here are the steps to install mod_wsgi on Ubuntu / Debian systems.

1. Install prerequisites

Open terminal and run the following commands

$ sudo apt-get update
$ sudo apt-get install apache2 apache2-utils libexpat1 ssl-cert python

Bonus Read : How to Increase Max URL length in Apache

2. Install mod_wsgi module in Ubuntu

Next, install mod_wsgi in Ubuntu for Apache.

$ sudo apt-get install libapache2-mod-wsgi

Bonus Read : How to Increase Max Connections in Apache

3. Restart Apache Server

Restart Apache server to apply changes

$ sudo systemctl restart apache2

4. Configure mod_wsgi for Apache

Next we will create a sample python script to run using mod_wsgi. Open terminal and run the following command to create a new python file.

$ sudo vi /var/www/html/test_script.py

Add the following lines to it

def application(environ,start_response):
    status = '200 OK'
    html = '\n' \
           '\n' \
           ' mod_wsgi is working\n' \
           '\n' \
           '\n'
    response_header = [('Content-type','text/html')]
    start_response(status,response_header)
    return [html]

Save and close the file.

Bonus Read : How to Configure Apache Load Balancer

We need to create a separate Apache configuration file to serve our python script over HTTP.

$ sudo vi /etc/apache2/conf-available/mod-wsgi.conf

Add the following line to mod-wsgi.conf file

WSGIScriptAlias /test_wsgi /var/www/html/test_script.py

Run the following command to enable wsgi configuration. Please make sure that the name of your module mentioned after a2enconf is same as that of your configuration file without extension (e.g. mod-wsgi).

$ sudo a2enconf mod-wsgi
$ sudo systemctl restart apache2

Bonus Read : Apache Reverse Proxy Configuration for Ubuntu/Debian

4. Test mod_wsgi configuration

You can test your mod_wsgi configuration by visiting http://your_server_ip/test_wsgi on your browser. You should see the message “mod_wsgi is working“.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!