美文网首页Python
在 CentOS 上使用 NGINX + Gunicorn, S

在 CentOS 上使用 NGINX + Gunicorn, S

作者: 斐然成章 | 来源:发表于2018-09-02 11:57 被阅读9次

    选用 CentOS 7.5 版本部署 Flask 站点,需要安装的 Software Packages 有:

    • nginx
    • gunicorn
    • supervisor
    • flask

    Nginx

    Nginx是一个异步框架的Web服务器,也可以用作反向代理,负载均衡器和 HTTP 缓存。该软件由 Igor Sysoev 创建,并于2004年首次公开发布。

    安装

    # yum -y install epel-release
    # yum -y install nginx
    

    启动

    # systemctl enable nginx
    # systemctl start nginx
    # systemctl status nginx
    

    操作
    在修改 nginx.conf 配置后,先测试修改后的配置文件是否正确。

    # nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    

    如果返回 ok, 再执行 nginx -s reload 重新加载配置文件。
    默认的配置文件位于 /etc/nginx/nginx.conf, 也可以设置配置文件: nginx -c filename

    Gunicorn

    Green Unicorn 是用于 UNIX 的 Python WSGI HTTP,是 pre-fork 多进程工作模型。

    安装

    # yum -y install python-pip
    # pip install gunicorn
    # pip install gevent
    

    示例

    # cat test.py
    def app(environ, start_response):
        """Simplest possible application object"""
        data = b'Hello Dragon!\n'
        status = '200 OK'
        response_headers = [
            ('Content-type', 'text/plain'),
            ('Content-Length', str(len(data)))
        ]
        start_response(status, response_headers)
        return iter([data])
    # gunicorn --workers=2 test:app
    

    Supervisor

    Supervisor 是一个使用 Python 写的 C/S 架构的进程管理工具,它可以很方便的启动、停止、重启一个或多个进程。如果 Supervisor 管理的进程意外被杀死,它会将该进程重新拉起。

    安装

    # pip install supervisor
    # yum -y install supervisor
    

    启动

    # systemctl enable supervisord
    # systemctl start supervisord
    

    Flask

    Flask 是一个使用 Python 编写的轻量级 Web应用框架。基于 Werkzeug WSGI 工具箱和 Jinja2 模板引擎

    安装

    # pip install Flask
    

    Example

    项目部署目录结构:

    # mkdir -p /feiran/{etc,lib,log,run}
    # tree /feiran
    /feiran
    ├── etc
    ├── lib
    ├── log
    └── run
    

    项目命名为 dragon

    # cat /feiran/lib/dragon/dragon.py
    from flask import Flask
    app = Flask("Dragon")
    
    @app.route("/")
    def dragon():
        return "Hi, Dragon!"
    
    if __name__ == '__main__':
        app.debug = True
        app.run()
    

    使用 Supervisor 管理 Gunicorn 进程

    # cat /etc/supervisord.d/dragon.ini
    [program:dragon]
    environment=PYTHONPATH='/feiran/lib/dragon'
    stdout_logfile=/feiran/log/dragon_gunicorn.log
    autostart=true
    autorestart=unexpected
    redirect_stderr=true
    stopsignal=QUIT
    command=gunicorn -c /feiran/etc/dragon_gunicorn.py dragon:app
    

    Gunicorn 的配置文件, Async Workers:gevent

    # cat /feiran/etc/dragon_gunicorn.py
    import multiprocessing
    
    workers = multiprocessing.cpu_count() * 2 + 1
    worker_class = "gunicorn.workers.ggevent.GeventWorker"
    worker_connections = 4096
    
    # Wait keepalive connection for 30 seconds
    keepalive = 30
    timeout = 600
    graceful_timeout = 12000
    loglevel = "error"
    access_logfile = "/feiran/log/dragon_gunicorn.log"
    bind = ["unix:/feiran/run/dragon_gunicorn.sock", "0.0.0.0:8080"]
    pidfile = "/feiran/run/dragon_gunicorn.pid"
    

    执行 systemctl restart supervisord
    执行 supervisorctl start dragon 启动 dragon 服务
    执行 supervisorctl status dragon 查看 dragon 状态

    最后一步,使用 Nginx 作为反向代理

    # cat /etc/nginx/nginx.conf
    # For more information on configuration, see:
    #   * Official English Documentation: http://nginx.org/en/docs/
    #   * Official Russian Documentation: http://nginx.org/ru/docs/
    
    user nginx;
    worker_processes auto;
    error_log /var/log/nginx/error.log;
    pid /run/nginx.pid;
    
    events {
        worker_connections 1024;
    }
    
    http {
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';
    
        access_log  /var/log/nginx/access.log  main;
    
        sendfile            on;
        tcp_nopush          on;
        tcp_nodelay         on;
        keepalive_timeout   65;
        types_hash_max_size 2048;
    
        include             /etc/nginx/mime.types;
        default_type        application/octet-stream;
    
        upstream gunicorn {
            server unix:/feiran/run/dragon_gunicorn.sock fail_timeout=5;
        }
    
        server {
            listen       80 default_server;
            listen       [::]:80 default_server;
            server_name  _;
            root         /usr/share/nginx/html;
    
            location / {
                set $upstream 'gunicorn';
    
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
    
                proxy_pass http://$upstream;
            }
    
            error_page 404 /404.html;
                location = /40x.html {
            }
    
            error_page 500 502 503 504 /50x.html;
                location = /50x.html {
            }
        }
    }
    

    修改 nginx.conf 修改后,记得执行 nginx -tnginx -s reload

    测试 Flask 站点

    dragon.png

    Flask 站点上线后的目录结构

    # tree /feiran/
    /feiran/
    ├── etc
    │   └── dragon_gunicorn.py
    ├── lib
    │   └── dragon
    │       ├── dragon.py
    │       └── dragon.pyc
    ├── log
    │   └── dragon_gunicorn.log
    └── run
        ├── dragon_gunicorn.pid
        └── dragon_gunicorn.sock
    
    5 directories, 6 files
    

    参考资料

    http://nginx.org/en/docs/
    https://gunicorn.org/
    http://docs.gunicorn.org/en/stable/
    http://supervisord.org/
    http://flask.pocoo.org/

    相关文章

      网友评论

        本文标题:在 CentOS 上使用 NGINX + Gunicorn, S

        本文链接:https://www.haomeiwen.com/subject/mcfmwftx.html