Configure Nginx with uWSGI
Ningx and uWSGI are powerful tools on their category. Nginx is a web server and reverse-proxy that can serve static files, change the request, cache content, apply rate limiting and lots of features. on the other hand uWSGI is an application server. it runs a web application, when a request comes in handles it and passes the response.
There’s a specification called WSGI (Web Server Gateway Interface) which describes how web servers and Python web applications should communicate with each other. uWSGI has its own protocol called uwsgi which implmenets WSGI.
uWSGI claims that it’s capable of handling requests without a need to a web server however Nginx features are tempting to not to use it,
Nginx can communicate with uWSGI in uwsgi protocol.
There’re a few ways to run uWSGI with Nginx.
Unix (uWSGI) Socket
Run the app
uwsgi --socket myapp.sock -w main:app
Replace the content of /etc/sites-available/default with the following block and restart Nginx.
upstream myapp {
server unix:///home/project/myapp.sock;
}
server {
listen 8000;
location / {
include uwsgi_params; // Include directives in /etc/nginx/uwsgi_params
uwsgi_pass myapp; // pass every request to the server in uwsgi protocol
}
}
Nginx can communicate with uWSGI in uwsgi protocol
TCP Socket
The next option is to use TCP (port) socket. this way there’s more overhead comparing to previous way since this socket is over network.
Run the app
uwsgi --socket 127.0.0.1:8001 -w main:app
Replace the content of /etc/sites-available/default with the following block and restart Nginx.
upstream myapp {
server 127.0.0.1:8001
}
server {
listen 8000;
location / {
include uwsgi_params;
uwsgi_pass myapp;
}
}
Native HTTP
In the mentioned configurations, Nginx communicates with uWSGI in uwsgi protocol. if we were to use another web server that doesn’t support uwsgi protocol, we could use --http-socket this is for web servers who are able to speak to upstream HTTP proxies. this way uWSGI speaks natively in HTTP.
Standalone Mode
The last option is to run uWSGI in standalone mode which a web server is not neeed.
Run the app
uwsgi --http 127.0.0.1:8001 -w main:app
Virtual Hosting
There’s concept called virtual hosting meaning that a machine can serve multiple websties. take the following as an example
server {
listen 80;
server_name myapp.localhost;
charset utf-8;
...
}
server {
listen 80;
server_name test.myapp.localhost;
charset utf-8;
...
}
Nginx listens on port 80 and route the requests to the server based on the request server name.