About

Gunicorn is the abbreviation of Green Unicorn, a WSGI Http server for Python under Unix systems. Its advantage is that it is relatively simple and easy to use on other web frameworks, such as flask, Django, etc.

Install & Start

pip install gunicorn

Install gunicorn using the above command, then write a simple python script to start the service

# myapp.py
def app(environ, start_response):
    data = b"Hello, World!\n"
    start_response("200 OK",[("Content-Type","text/plain"),("Content-Length",str(len(data)))])
    return iter([data])
# Start:
gunicorn -w 4 myapp:app

Console output:

[2021-04-11 20:59:22 +0800] [32842] [INFO] Starting gunicorn 20.1.0
[2021-04-11 20:59:22 +0800] [32842] [INFO] Listening at: http://127.0.0.1:8000 (32842)
[2021-04-11 20:59:22 +0800] [32842] [INFO] Using worker: sync
[2021-04-11 20:59:22 +0800] [32844] [INFO] Booting worker with pid: 32844
[2021-04-11 20:59:22 +0800] [32845] [INFO] Booting worker with pid: 32845
[2021-04-11 20:59:22 +0800] [32846] [INFO] Booting worker with pid: 32846
[2021-04-11 20:59:22 +0800] [32847] [INFO] Booting worker with pid: 32847

Deploy

Gunicorn is a WSGI HTTP server. When using Gunicorn, it is best to put it behind an HTTP proxy server. The official recommendation is to use Nginx. A simple Nginx configuration is as follows:

  server {
    listen 80;
    server_name example.org;
    access_log  /var/log/nginx/example.log;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
  }

Here, Nginx is set up as a reverse proxy server for the Gunicorn server running on localhost port 8000.