Sign up for our newsletter.
Get the latest tutorials on SysAdmin and open source topics.
Installing mod_wsgi on Ubuntu 12.04
This article covers a version of Ubuntu that is no longer supported. If you are currently operate a server running Ubuntu 12.04, we highly recommend upgrading or migrating to a supported version of Ubuntu:
Reason: Ubuntu 12.04 reached end of life (EOL) on April 28, 2017 and no longer receives security patches or updates. This guide is no longer maintained.
This guide might still be useful as a reference, but may not work on other Ubuntu releases. If available, we strongly recommend using a guide written for the version of Ubuntu you are using. You can use the search functionality at the top of the page to find a more recent version.
mod_wsgi is a simple and easy to setup tool that serves python web apps from Apache server. It is also one of the recommended ways of getting Django into production. In this article, we will be discussing the installation and set up of mod_wsgi with the Apache server.
This article is the second in a series of 3. The previous article covers installing Django on the server. I recommend looking over the previous article before starting this one.
Since we are focusing on mod_wsgi for installing Apache module so first of all we need an installed Apache server. Use below command for installing required Apache components.
Once all of the components of apache have installed, access your droplet IP in the browser and make sure that you see the default Apache page that says ‘It Works’. If you don’t get this page , it may be for one of several reasons
- Apache is not installed correctly
- There is an existing installation of Apache
- Iptables are blocking the port number 80
Check the issue and make sure that Apache is working properly before moving to the next step.
Installing mod_wsgi From Aptitude:
It is very easy to install mod_wsgi with the help of aptitude.
Restart Apache to get mod_wsgi to work.
How to Install mod_wsgi from Source
Since the code is constantly changing, we can ensure that we install the latest version of mod_wsgi by installing it from the source.
Before continuing further, we will grab two different packages from aptitude.
If you are using worker MPM with Apache then replace apache2-prefork-dev with apache2-threaded-dev.
After that process has completed, you can go ahead and configure and install mod_wsgi.
Once you have mod_wsgi installed, you can see how to use it to serve applications in the next article.
Предложение от 8host.com
Установка mod_wsgi в Ubuntu 12.04
Что такое mod_wsgi?
mod_wsgi – это простой в установке и использовании инструмент модуль Apache, позволяющий обслуживать приложения Python. Кроме того, это один из рекомендуемых способов запуска приложения Django в производство. В данном руководстве речь пойдет об установке и настройке mod_wsgi на веб-сервере Apache.
Прежде чем приступить к выполнению этого руководства, рекомендуется прочесть предыдущую статью данной серии, которая демонстрирует установку Django на сервер Ubuntu 12.04.
Конечно, также понадобится предварительно установленный сервер Apache. Для установки Apache и всех необходимых компонентов используйте:
sudo aptitude install apache2 apache2.2-common apache2-mpm-prefork apache2-utils libexpat1 ssl-cert
По завершении установки Apache и компонентов, откройте при помощи браузера IP сервера; если установка Apache прошла успешно, на экране появится стандартная страница «It Works». Если же такая страница не появилась, возможно:
- Веб-сервер Apache установлен неверно;
- На сервере существует ранее установленная версия Apache;
- Фаервол Iptables блокирует порт 80.
Запустив Apache, приступайте к выполнению руководства.
Установка mod_wsgi с помощью aptitude
Установить mod_wsgi при помощи aptitude очень просто.
sudo aptitude install libapache2-mod-wsgi
Затем перезапустите Apache:
sudo service apache2 restart
Установка mod_wsgi из исходного кода
Исходный код постоянно меняется, тем самым обеспечивая установку последней доступной версии модуля.
Итак, чтобы скомпилировать mod_wsgi из исходного кода, выполните:
tar xvfz mod_wsgi-3.3.tar.gz
Затем загрузите при помощи aptitude два пакета:
sudo aptitude install python-dev apache2-prefork-dev
При использовании рабочего MPM замените apache2-prefork-dev на apache2-threaded-dev.
После завершения этого процесса можно установить mod_wsgi:
sudo make install
Установив mod_wsgi, читайте следующую статью, в которой речь идет об обслуживании приложений Python при помощи данного модуля.
Installing mod_wsgi for Python3 on Ubuntu
Could anyone give me a clear set of instructions for installing mod_wsgi on Ubuntu for Python 3?
I did get Flask & mod_wsgi successfully using Python3, and for a brief moment felt happy.
apt-get is installing an out of date version of libapache2-mod-wsgi-py3 and this is causing errors in Apache’s log. (Should I report this and if so where?)
In the link, the engineer is using pip to install a more up-to-date version.
Interestingly, he appears to be installing it into a virtual Python3 environment. (Would this be any different than using the system pip3 ?)
Also he uses pip3 install mod_wsgi , but pip3 search mod_wsgi returns:
(EDIT: no he doesn’t, he uses pip not pip3. Can that be right? Has he got his wires crossed? Isn’t pip going to ignore the fact that he is in his py3venv and simply use the system’s py2 installation? But anyway that doesn’t resolve the confusion. )
So what is mod_wsgi-httpd ? And is it certain this isn’t the one I want?
Finally, can anyone provide a link to installing mod_wsgi from source?
EDIT: I don’t get why the engineer is using pip install mod_wsgi rather than pip3 . . Surely that can’t be right? But if I do use pip3, I get:
And now I try pip3 install mod_wsgi-httpd , it takes about five minutes to compile:
So now I’m worried I’ve got a second Apache sitting in my Py3 virtualenv.
However that does get rid of the error; pip3 install mod_wsgi now completes successfully.
EDIT: but now I have come completely unstuck trying to follow his instructions: I don’t have a /etc/apache2/mods-available/wsgi_express.load , and if he is suggesting making it, then for a start this seems arbitrary, and secondly the text he suggests putting in it, i.e. LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi-py34.cpython-34m.so — this file doesn’t exist on my system.
I do have /etc/apache2/mods-available/wsgi.load
Drowning in technology again, can someone throw me a line?
2 Answers 2
If they had activated the Python 3 virtual environment and its bin directory was in there path, then likely they could simply run ‘pip’ rather than ‘pip3’. You should run ‘which pip’ to verify whether it was coming from the virtual environment you expect.
The ‘mod_wsgi-httpd’ package is specifically for installing a distinct instance of Apache itself to get around issues where the system wide Apache is out of date or missing development header files, or otherwise can’t modify the system wide configuration. It is generally of more relevance when you don’t have root access to fix system wide issues and are only interested in running on an unprivileged port and so do not need root access. You would also have to be using ‘mod_wsgi-express’ from the ‘mod_wsgi’ package which was ‘pip’ installed after ‘mod_wsgi-httpd’ had been installed as that is the only way to use ‘mod_wsgi-httpd’ installed version of Apache.
So, for ‘mod_wsgi-httpd’ you would really want to ignore it. If you have already installed it, then ‘pip’ uninstall both it and ‘mod_wsgi’. The latter needs to be uninstalled as it will be bound to the ‘mod_wsgi-httpd’ Apache version and the ‘mod_wsgi.so’ will not work with the system wide.
As to separate users steps in link, they look correct, although I would say that in step 3, it should be highlighted that the LoadModule and WSGIPythonHome lines to be added are what is output when running mod_wsgi-express install-module command. What are output is customised to match what your installation should be. So don’t make up values, just use what that command output.
Install and Configure mod_wsgi on Ubuntu 16.04
Table of Contents
mod_wsgi is an Apache module that provides a standard and efficient method for dynamic web applications to communicate with Apache web servers. mod_wsgi is a simple to use module that can be used to host any Python web application which supports the Python WSGI specification. It is used to deploy applications written with different tools such as Django, TurboGears, and Flask.
In this tutorial, we will demonstrate the installation and set up of mod_wsgi with the Apache web server on Ubuntu 16.04.
- Ubuntu 16.04 server installed on your system.
- Non-root user account with sudo privilege set up on your system.
Let’s start making sure that your Ubuntu 16.04 server is fully up to date. You can update your server by running the following command:
Before starting, you will need to install some prerequisite Apache components in order to work with mod_wsgi. You can install all required components by simply running the following command:
Once all of the Apache components have installed, use the curl command to verify the Apache server is responding.
You should see the default Ubuntu Apache page.
Now, install mod_wsgi by running the following command:
Restart Apache service to get mod_wsgi to work.
Creating WSGI website
To serve the python application, it is important that Apache forward certain types of requests to mod_wsgi. It is also important to create a python file that tells mod_wsgi how to handle these requests.
You can do this by creating a website for WSGI that will tell Apache the location of python file and setup the file accordingly.
Next, create a python test script which you set above.
When you are finished save and close the file.
Once you are done with it, you will need to enable the WSGI configuration and restart Apache.
If everything goes as expected, open your favorite web browser and type the URL http://your-server-ip/test_wsgi and hit Enter , You will get the newly created application:
You have installed and configured mod_wsgi with Apache and verified a WSGI Python test page. Feel free to comment below if you have any questions or run into any issues following the tutorial.
pip install mod-wsgi Copy PIP instructions
Installer for Apache/mod_wsgi.
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: Apache Software License (Apache License, Version 2.0)
Tags mod_wsgi, wsgi, apache
- Development Status
- 6 — Mature
- OSI Approved :: Apache Software License
- Operating System
- MacOS :: MacOS X
- POSIX :: BSD
- POSIX :: Linux
- POSIX :: SunOS/Solaris
- Programming Language
- Python :: 2.6
- Python :: 2.7
- Python :: 3.3
- Python :: 3.4
- Python :: 3.5
- Python :: 3.6
- Python :: 3.7
- Python :: 3.8
- Python :: Implementation :: CPython
- Internet :: WWW/HTTP :: WSGI
- Internet :: WWW/HTTP :: WSGI :: Server
The mod_wsgi package provides an Apache module that implements a WSGI compliant interface for hosting Python based web applications on top of the Apache web server.
Installation of mod_wsgi from source code can be performed in one of two ways.
The first way of installing mod_wsgi is the traditional way that has been used by many software packages. This is where it is installed as a module directly into your Apache installation using the commands configure, make and make install, a method sometimes referred to by the acronym CMMI. This method works with most UNIX type systems. It cannot be used on Windows.
The second way of installing mod_wsgi is to install it as a Python package into your Python installation using the Python pip install command. This can be used on all platforms, including Windows.
This second way of installing mod_wsgi will compile not only the Apache module for mod_wsgi, but will also install a Python module and admin script, which on UNIX type systems can be used to start up a standalone instance of Apache directly from the command line with an auto generated configuration.
This later mechanism for installing mod_wsgi using Python pip is a much simpler way of getting starting with hosting your Python web application. In particular, this installation method makes it very easy to use Apache/mod_wsgi in a development environment without the need to perform any Apache configuration yourself.
The Apache module for mod_wsgi created when using the pip install method can still be used with the main Apache installation, via manual configuration if necessary. As detailed later in these instructions, the admin script installed when you use pip install can be used to generate the configuration to manually add to the Apache configuration to load mod_wsgi.
Note that although MacOS X is a UNIX type system, the pip install method is the only supported way for installing mod_wsgi.
Since MacOS X Sierra, Apple has completely broken the ability to install third party Apache modules using the apxs tool normally used for this task. History suggests that Apple will never fix the problem as they have broken things in the past in other ways and workarounds were required as they never fixed those problems either. This time there is no easy workaround as they no longer supply certain tools which are required to perform the installation.
The pip install method along with the manual configuration of Apache is also the method you need to use on Windows.
With either installation method for mod_wsgi, you must have Apache installed. This must be a complete Apache installation. It is not enough to have only the runtime packages for Apache installed. You must have the corresponding development package for Apache installed, which contains the Apache header files, as these are required to be able to compile and install third party Apache modules.
Similarly with Python, you must have a complete Python installation which includes the corresponding development package, which contains the header files for the Python library.
If you are running Debian or Ubuntu Linux with Apache 2.2 system packages, and were using the Apache prefork MPM you would need both:
If instead you were using the Apache worker MPM, you would need both:
If you are running Debian or Ubuntu Linux with Apache 2.4 system packages, regardless of which Apache MPM is being used, you would need both:
If you are running RHEL, CentOS or Fedora, you would need both:
If you are using the Software Collections Library (SCL) packages with RHEL, CentOS or Fedora, you would need:
If you are running MacOS X, Apache is supplied with the operating system. If running a recent MacOS X version, you will though need to have the Xcode command line tools installed as well as the Xcode application. The command line tools can be installed by running xcode-select --install . The Xcode application can be installed from the MacOS X App Store. If you are using older MacOS X versions, you may be able to get away with having just the command line tools.
If you are running Windows, it is recommended you use the Apache distribution from Apache Lounge (www.apachelounge.com). Other Apache distributions for Windows aren’t always complete and are missing the files needed to compile additional Apache modules. By default, it is expected that Apache is installed in the directory C:/Apache24 on Windows.
If you are on Linux, macOS or other UNIX type operating system and can’t or don’t want to use the system package for Apache, you can use pip to install mod_wsgi, but you should use use the mod_wsgi-standalone package on PyPi instead of the mod_wsgi package.
Installation into Apache
For installation directly into your Apache installation using the CMMI method, see the full documentation at:
Alternatively, use the following instructions to install mod_wsgi into your Python installation and then either copy the mod_wsgi module into your Apache installation, or configure Apache to use the mod_wsgi module from the Python installation.
When using this approach, you will still need to manually configure Apache to have mod_wsgi loaded into Apache, and for it to know about your WSGI application.
Installation into Python
To install mod_wsgi directly into your Python installation, from within the source directory of the mod_wsgi package you can run:
This will compile mod_wsgi and install the resulting package into your Python installation.
If wishing to install an official release direct from the Python Package Index (PyPi), you can instead run:
If you wish to use a version of Apache which is installed into a non standard location, you can set and export the APXS environment variable to the location of the Apache apxs script for your Apache installation before performing the installation.
If you are using Linux, macOS or other UNIX type operating system, and you don’t have Apache available, you can instead install mod_wsgi using:
When installing mod_wsgi-standalone , it will also install a version of Apache into your Python distribution. You can only use mod_wsgi-express when using this variant of the package. The mod_wsgi-standalone package follows the same version numbering as the mod_wsgi package on PyPi.
If you are on Windows and your Apache distribution is not installed into the directory C:/Apache24 , first set the environment variable MOD_WSGI_APACHE_ROOTDIR to the directory containing the Apache distribution. Ensure you use forward slashes in the directory path. The directory path should not include path components with spaces in the name.
Note that nothing will be copied into your Apache installation at this point. As a result, you do not need to run this as the root user unless installing it into a site wide Python installation rather than a Python virtual environment. It is recommended you always use Python virtual environments and never install any Python package directly into the system Python installation.
On a UNIX type system, to verify that the installation was successful, run the mod_wsgi-express script with the start-server command:
This will start up Apache/mod_wsgi on port 8000. You can then verify that the installation worked by pointing your browser at:
When started in this way, the Apache web server will stay in the foreground. To stop the Apache server, use CTRL-C.
For a simple WSGI application contained in a WSGI script file called wsgi.py, in the current directory, you can now run:
This instance of the Apache web server will be completely independent of, and will not interfere with any existing instance of Apache you may have running on port 80.
If you already have another web server running on port 8000, you can overr >—port option:
For a complete list of options you can run:
For further information related to using mod_wsgi-express see the main mod_wsgi documentation.
Non standard Apache installations
Many Linux distributions have a tendency to screw around with the standard Apache Software Foundation layout for installation of Apache. This can include renaming the Apache httpd executable to something else, and in addition to potentially renaming it, replacing the original binary with a shell script which performs additional actions which can only be performed as the root user.
In the case of the httpd executable simply being renamed, the executable will obviously not be found and mod_wsgi-express will fail to start at all.
In this case you should work out what the httpd executable was renamed to and use the --httpd-executable option to specify its real location.
For example, if httpd was renamed to apache2, you might need to use:
In the case of the httpd executable being replaced with a shell script which performs additional actions before then executing the original httpd executable, and the shell script is failing in some way, you will need to use the location of the original httpd executable the shell script is in turn executing.
Running mod_wsgi-express as root
The primary intention of mod_wsgi-express is to make it easier for users to run up Apache on non privileged ports, especially during the development of a Python web application. If you want to be able to run Apache using mod_wsgi-express on a privileged port such as the standard port 80 used by HTTP servers, then you will need to run mod_wsgi-express as root. In doing this, you will need to perform additional steps.
The first thing you must do is supply the --user and --group options to say what user and group your Python web application should run as. Most Linux distributions will predefine a special user for Apache to run as, so you can use that. Alternatively you can use any other special user account you have created for running the Python web application:
This approach to running mod_wsgi-express will be fine so long as you are using a process supervisor which expects the process being run to remain in the foreground and not daemonize.
If however you are directly integrating into the system init scripts where separate start and stop commands are expected, with the executing process expected to be daemonized, then a different process is required to setup mod_wsgi-express .
In this case, instead of simply using the start-server command to mod_wsgi-express you should use setup-server :
In running this command, it will not actually startup Apache. All it will do is create the set of configuration files and the startup script to be run.
So that these are not created in the default location of a directory under /tmp, you should use the --server-root option to specify where they should be placed.
Having created the configuration and startup script, to start the Apache instance you can now run:
To subsequently stop the Apache instance you can run:
You can also restart the Apache instance as necessary using:
Using this approach, the original options you supplied to setup-server will be cached with the same configuration used each time. If you need to update the set of options, run setup-server again with the new set of options.
Note that even taking all these steps, it is possible that running up Apache as root using mod_wsgi-express may fail on systems where SELinux extensions are enabled. This is because the SELinux profile may not match what is being expected for the way that Apache is being started, or alternatively, the locations that Apache has been specified as being allowed to access, don’t match where the directory specified using the --server-root directory was placed. You may therefore need to configure SELinux or move the directory used with --server-root to an allowed location.
In all cases, any error messages will be logged to a file under the server root directory. If you are using mod_wsgi-express with a process supervisor, or in a container, where log messages are expected to be sent to the terminal, you can use the --log-to-terminal option.
Using mod_wsgi-express with Django
To use mod_wsgi-express with Django, after having installed the mod_wsgi package into your Python installation, edit your Django settings module and add mod_wsgi.server to the list of installed apps.
To prepare for running mod_wsgi-express , ensure that you first collect up any Django static file assets into the directory specified for them in the Django settings file:
You can now run the Apache server with mod_wsgi hosting your Django application by running:
If working in a development environment and you would like to have any code changes automatically reloaded, then you can use the --reload-on-changes option.
If wanting to have Apache started as root in order to listen on port 80, instead of using mod_wsgi-express setup-server as described above, use the --setup-only option to the runmodwsgi management command.
This will set up all the required files and you can use apachectl to start and stop the Apache instance as explained previously.
Connecting into Apache installation
If you want to use mod_wsgi in combination with your system Apache installation, the CMMI method for installing mod_wsgi would normally be used.
If you are on MacOS X Sierra that is no longer possible. Even prior to MacOS X Sierra, the System Integrity Protection (SIP) system of MacOS X, prevented installing the mod_wsgi module into the Apache modules directory.
If you are using Windows, the CMMI method was never supported as Windows doesn’t supply the required tools to make it work.
The CMMI installation method also involves a bit more work as you need to separately download the mod_wsgi source code, run the configure tool and then run make and make install.
The alternative to using the CMMI installation method is to use the Apache mod_wsgi module created by running pip install. This can be directly referenced from the Apache configuration, or copied into the Apache modules directory.
To use the Apache mod_wsgi module from where pip install placed it, run the command mod_wsgi-express module-config . This will output something like:
These are the directives needed to configure Apache to load the mod_wsgi module and tell mod_wsgi where the Python installation directory or virtual environment was located.
This would be placed in the Apache httpd.conf file, or if using a Linux distribution which separates out module configuration into a mods-available directory, in the wsgi.load file within the mods-available directory. In the latter case where a mods-available directory is used, the module would then be enabled by running a2enmod wsgi as root. If necessary Apache can then be restarted to verify the module is loading correctly. You can then configure Apache as necessary for your specific WSGI application.
Note that because in this scenario the mod_wsgi module for Apache could be located in a Python virtual environment, if you destroy the Python virtual environment the module will also be deleted. In that case you would need to ensure you recreate the Python virtual environment and reinstall the mod_wsgi package using pip, or, take out the mod_wsgi configuration from Apache before restarting Apache, else it will fail to startup.
Instead of referencing the mod_wsgi module from the Python installation, you can instead copy the mod_wsgi module into the Apache installation. To do that, run the mod_wsgi-express install-module command, running it as root if necessary. This will output something like:
This is similar to above except that the mod_wsgi module was copied to the Apache modules directory first and the LoadModule directive references it from that location. You should take these lines and configure Apache in the same way as described above.
Do note that copying the module like this will not work on recent versions of MacOS X due to the SIP feature of MacOS X.