how to use nginx in python

To use nginx with Python, we require the WSGI interface. WSGI is a Python specification which describes how a web server communicates with a Python web application. Nginx does not support WSGI protocol natively. Therefore we require an interface between Nginx and our Python application. One such widely used interface is uWSGI.

Here are step-by-step instructions to use Nginx with Python using uWSGI:

  1. Install Nginx and uWSGI
main.py
sudo apt-get install nginx uwsgi uwsgi-plugin-python3
54 chars
2 lines
  1. Create a new Flask application (or any other web framework of your choice)
main.py
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

if __name__ == "__main__":
    app.run()
145 chars
10 lines
  1. Create a uWSGI configuration file uwsgi.ini which points to your Flask application entry point
main.py
[uwsgi]
module = myapp:app
master = true
processes = 5
socket = myapp.sock
chmod-socket = 660
vacuum = true
die-on-term = true
127 chars
9 lines
  1. Start uWSGI using the configuration file created above
main.py
uwsgi --ini uwsgi.ini
22 chars
2 lines
  1. Create a new Nginx server block in /etc/nginx/sites-available/default which proxies requests to the uWSGI socket above
main.py
server {
    listen 80;
    server_name example.com;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/path/to/myapp.sock;
    }
}
154 chars
10 lines
  1. Restart Nginx server
main.py
sudo systemctl restart nginx
29 chars
2 lines

Now your Python application should be running with Nginx as a reverse proxy.

gistlibby LogSnag