This article as a learning record, I will find useful articles and methods to record, please visit the original

1. Install Gunicorn first

pip install gunicorn
Copy the code

2. Add the following to app.run() of the entry file

from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
Copy the code

Ex. :

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World! '

if __name__ == '__main__':
    from werkzeug.contrib.fixers import ProxyFix
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.run()
Copy the code

3. Start Gunicorn

The easiest way to do this is

Gunicorn entry file name :appCopy the code

The default is to listen on 127.0.0.1:8000

If you want to handle high concurrency, open multiple processes and modify the drawing of the listening port

Gunicorn -w 4-b 127.0.0.1:8000 Entry file name :appCopy the code

In this way, four processes can be started to process HTTP requests simultaneously, improving the efficiency and performance of the system. You can also change port 8000 to something else

In practice, the service should be started by background execution

Nohup Command to start the service &Copy the code

namely

Nohup gunicorn -w 4-b 127.0.0.1:8000 Entry file name :app &Copy the code

You can then access 127.0.0.1:8000 in your native browser, which will display Hello World!

Note: If you want to access through the Internet, change the IP address to the internal IP address

4. Configure nginx

Configuration to

server {
    listen 80;
    server_name example.org; This is the external domain name of the HOST machineLocation / {proxy_pass http://127.0.0.1:8000;# here is the service address pointing to Gunicorn Host
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}Copy the code

This will enable port 80 to be forwarded to port 8000 after startup

5. Check the configuration

nginx -t
Copy the code

If the following information is displayed, the configuration is successful

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Copy the code

Update the nginx configuration

nginx -s reload
Copy the code

With Gunicorn already running, a browser visit to 127.0.0.1 will bring up Hello World! the

7. Restart Gunicorn

Type the command

pstree -ap|grep gunicorn
Copy the code

kill -HUP 30693
Copy the code