setup uwsgi in nginx python

How to Setup Uwsgi with NGINX for Python

uwsgi is an application container for web sites & applications. It is useful for hosting python applications and websites. In this article, we will learn how to setup uwsgi with NGINX for python.


How to Setup Uwsgi with NGINX for Python

Here are the steps to setup uwsgi with NGINX for python.


1. Install Python, Pip, NGINX

Open terminal and run the following command to install python, pip, NGINX. We will also update apt.

$ sudo apt-get update
$ sudo apt-get install python-dev python-pip nginx

Once pip is installed, you can use it to install virtualenv to create and manage python virtual environments.

$ sudo pip install virtualenv


2. Setup App Folder & Virtualenv

Next, we will create folder and virtual environment for application.

$ mkdir ~/myapp/

Go the newly created folder to create new virtual environment.

cd ~/myapp

Run the following command to create new virtual environment myenv

$ sudo virtualenv myenv

Activate the new virtual environment with the following command.

$ source myenv/bin/activate

You will notice that your prompt will change to indicate that you are working within your new virtual environment.

(myenv)username@host:~/my_app$

You can always deactivate your virtual environment with deactivate command.

Please note, whatever packages you install within a virtual environment can be accessible from only within that virtual environment. They will not be accessible from outside virtual environment or from other virtual environments.

Run the following command to install uwsgi.

$ pip install uwsgi


3. Create uwsgi application

Next, we will create a simple uwsgi application to host our python application.

Create a blank wsgi.py file within myapp folder to store our uwsgi application’s URL processing codes.

$ sudo vi ~/myapp/wsgi.py

Add the following lines to it, to display ‘hello world’ as response.

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ["<h1 style='color:blue'>Hello World!</h1>"]

In our case, we have used a simple request handler in wsgi.py file. In complex applications, we will simply link to the actual application’s URL processors. It basically listens to all incoming requests and sends the same response, for the sake of simplicity here. We use enivon variable to specify a key-value object, and start_response to render response.

Start uwsgi server on port 8080, with the following command.

$ uwsgi --socket 0.0.0.0:8080 --protocol=http -w wsgi

Now if you open browser and visit your server’s domain or IP address followed by 8080 port number then you will see the message ‘Hello World!’.

At the point, you can deactivate your virtual environment if you want. But if you want to close the above server, you will need to activate your virtual environment once again.


4. Configure uwsgi config file

As you might have noticed above, we have passed some parameters as options, while calling uwsgi command. If you want to avoid doing this every time, you can create a simple config file with those details, and pass its location in uwsgi call. Run the following command to create config file.

$ sudo vi ~/myapp/myapp.ini

Add the section [uwsgi] to identify our application.

[uwsgi]
module = wsgi:application

Add the following lines to mark initial process as master, and start 5 workers.

master = true
processes = 5

Add the following lines to create a socket called myapp.sock, change file permissions and use vacuum option to close the socket when not in use.

socket = myapp.sock
chmod-socket = 664
vacuum = true

Lastly, add the following line to kill the processes when uwsgi is terminated.

die-on-term = true

Save and close the file. The entire file will look like.

[uwsgi]
module = wsgi:application

master = true
processes = 5

socket = myapp.sock
chmod-socket = 664
vacuum = true

die-on-term = true


5. Create Upstart File

We will create and place a simple .conf file in /etc/init so that our application runs on system boot and is always available. Create an empty file with the following command.

$ sudo vi /etc/init/myapp.conf

Add the following lines to it.

description "uWSGI instance to serve myapp"

start on runlevel [2345]
stop on runlevel [!2345]

setuid demo
setgid www-data


script
    cd /home/demo/myapp
    . myenv/bin/activate
    uwsgi --ini myapp.ini
end script

In the above code, we specify the app description first. Then we mention its runlevel for starting and stopping process. This will tell upstart to run the process on boot. Next, we set the group to www-data that is the default user group for NGINX. Since, we run the application from within a virtual environment, we will use a script directive to specify the exact location of application and also activate its virtual environment from within the script block.

Save and exit the file. Now you may start the application with the following command.

$ sudo start myapp

If you want to stop the upstart script, run the following command.

$ sudo stop myapp


6. Configure uwsgi with NGINX

Finally, we need to configure uwsgi with NGINX. In this case, NGINX will be listening to HTTP port 80. When it receives a request, it will pass the request to uwsgi listening on port 8080. uwsgi will process the request and return the response back to NGINX, which will serve the response back to the client.

Create the NGINX virtual host file for our application using the following command.

$ sudo vi /etc/nginx/sites-available/myapp

Add the following server block for our uwsgi application. Replace server_domain_or_IP with the server name or IP address of

server {
    listen 80;
    server_name server_domain_or_IP;

    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/home/demo/myapp/myapp.sock;
    }
}

As per our server block, NGINX will listen to ‘/’, that is, all incoming requests at this point. You can always add more location blocks to listen to different URL patterns. But if you do so, you will need to add appropriate request handlers in your uwsgi application. For now, we will keep things simple.

Next, enable the configuration with the following command.

$ sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled

Test the configuration for errors.

$ sudo service nginx configtest

Restart NGINX Server.

$ sudo service nginx restart

Open browser and go to http://server_domain_or_ip and you will see the message ‘Hello World!’.

Also read:

How to Check MySQL Version in Linux
How to Clear Temp Files in Ubuntu
Git Pull vs Fetch
How to Kill User Sessions in Ubuntu
Git Tags vs Branches

Leave a Reply

Your email address will not be published. Required fields are marked *