nginx+gunicorn+flask actual combat on Centos7

1. Install gunicorn/flask

pip install gunicorn flask

2. Write simple examples

from flask import Flask
app = Flask(__name__)
 
@app.route('/')
def hello():
    return "This is sample for nginx+gunicorn+flask!"
 
if __name__ == '__main__':
    app.run()

3. Run the wsgi server gunicorn

gunicorn hello:app

The default port is 8000, the gunicorn service access: http://127.0.0.1:8000

4. Install nginx

yum install nginx

5. Configure the default port of /etc/nginx/nginx.conf server to change to: 8080

location / {
}

change into:

location / {
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://127.0.0.1:8000;
            break;
        }
}

or modified to:

location / {
         try_files $uri @gunicorn_hello_app;
}
location @gunicorn_hello_app {
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:8000;
}

6. Start nginx and open the firewall port 8080

iptables -I INPUT -p tcp --dport 8080 -j ACCEPT

Method 1: Execute nginx directly, and access it through a browser: http://xxx:8080, you can access it normally

Method 2: nginx is started as a systemd service,

systemctl enable nginx
systemctl start nginx

Access through the browser: http://xxx:8080, "nginx error!" appears to
view the log, and an error is reported

 *9 connect() to 127.0.0.1:8000 failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: _, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "127.0.0.1:8080"

This is caused by SELinux of Linux system, execute the following command:

- 检查SELinux是否运行
getenforce

- 暂时关闭SELinux
setenforce Permissive

- 如果SELinux不允许关闭
setsebool -P httpd_can_network_connect 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324933732&siteId=291194637