Centos7上nginx+gunicorn+flask实战

1.安装gunicorn/flask

pip install gunicorn flask

2.编写简单示例

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.运行wsgi服务器gunicorn

gunicorn hello:app

缺省端口为8000,gunicorn服务访问:http://127.0.0.1:8000

4.安装nginx

yum install nginx

5.配置/etc/nginx/nginx.conf server缺省端口修改为:8080

location / {
}

修改为:

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;
        }
}

或者修改为:

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.启动nginx,开启防火墙8080端口

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

方式一:直接执行nginx,通过浏览器访问:http://xxx:8080,可以正常访问

方式二:nginx作为systemd服务启动,

systemctl enable nginx
systemctl start nginx

通过浏览器访问:http://xxx:8080,出现“nginx error!”
查看日志,报错

 *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"

这是Linux系统的SELinux引起的,执行下面命令:

- 检查SELinux是否运行
getenforce

- 暂时关闭SELinux
setenforce Permissive

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

猜你喜欢

转载自my.oschina.net/smallfan/blog/1801856