image
LP小透明

当你感到无聊的时候,就去学习,因为一旦你开始认真学习,就会立刻发现比学习有趣的事来打断你的学习

nginx+gunicorn+gevent+flask使用总结帖

LP小透明    2018-11-21 22:08

        服务器架构部署:nginx负责反向代理。并发更高,可以做负载均衡,可以做静态文件缓存,还可以限制 ip 访问的频率等等。nginx也能从一定程度防御DDOS攻击。

ngx_http_limit_req_module模块通过漏桶原理来限制单位时间内的请求数,一旦单位时间内请求数超过限制,就会返回503错误。配置需要在两个地方设置:

nginx.conf的http段内定义触发条件,可以有多个条件 
在location内定义达到触发条件时nginx所要执行的动作 
例如:

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; //触发条件,所有访问ip 限制每秒10个请求
    ...
    server {
        ...
        location  ~ \.php$ {
            limit_req zone=one burst=5 nodelay;   //执行的动作,通过zone名字对应
               }
           }
     }

 

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m; //触发条件
    ...
    server {
        ...
        location /download/ {
            limit_conn addr 1;    // 限制同一时间内1个连接,超出的连接返回503
                }
           }
     }

gunicorn: 一般用来管理多个进程,有进程挂了gunicorn可以把它拉起来,防止服务器长时间停止服务,还可以动态调整 worker  的数量,请求多的时候增加 worker 的数量,请求少的时候减少,这就是它的主要优点。

但是,Nginx反向代理 + Flask + gunicorn 架构存在解决获取用户真实ip问题。gunicorn本身的日志记录无法获得真实IP,app中,views.py视图函数无法通过request.remote_addr获取,因此。修改方法如下:

代码:views.py
def xx():
    addr = request.headers['X-Real-Ip'] if 'X-Real-Ip' in request.headers else request.remote_addr

就可以了。

o , 对了,貌似windows环境不能使用gunicorn,放到 flask 的根目录下(和 manage.py 在同一层级),至少我在安装的时候报错。

ModuleNotFoundError: No module named 'fcntl'

至于gunicorn的启动配置,建立配置文件gunicorn.conf,内容编辑如下:

import gevent.monkey
import multiprocessing
gevent.monkey.patch_all()

bind = "0.0.0.0:8000"
backlog = 2048

# 启动的进程数
workers = multiprocessing.cpu_count()
worker_class = 'gevent'
x_forwarded_for_header = 'X-FORWARDED-FOR'

# 同步响应最长处理时间
timeout = 30
pidfile = "log/gunicorn.pid"
accesslog = "log/access.log"
errorlog = "log/debug.log"
capture_output = True
daemon = True

# 配置HTTPS协议的密钥
certfile = 'full_chain.pem'
keyfile = 'private.key'

重启gunicorn的时候,可以查看一下 gunicorn.id 一般和日志文件放在一起了,例如我的就放在当前目录下的log/文件夹,重启服务的时候执行:

# 结束进程
kill -HUP 30080
# 重启服务
# gunicorn -k gevent -c gunicorn.conf manage:app

Nginx反向代理服务器的配置有很多可以参考。

server {
    listen 443;
    server_name neusncp.com; // 你的域名
    ssl on;
    
    
    ssl_certificate  cert.pem;// 改成你的证书的名字
    ssl_certificate_key cert.key;// 你的证书的名字
    ssl_session_timeout 5m;
    
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    location / {
        index index.html index.htm;
    }
}
server {
    listen 80;
    server_name neusncp.com;// 你的域名
    rewrite ^(.*)$ https://$host$1 permanent;// 把http的域名请求转成https
}

 

Last Modified: 2020-05-29 18:46
Views: 3.1K

[[total]] comments

Post your comment
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]Floor
  2. Click to load more...
  3. Post your comment