Nginx+uWSGI+Flask

最近中途接手一个Flask项目,在开发一个月报表接口中,由于要先查询一个数据库本月记录,然后拿这些符合条件的id去另外一个数据库里联表查询,这样导致接口的处理时间过长,大约需要80s才能给前端返回数据,所以很明显,这时nginx已经超时返回504了。

我们查看nginx的error.log,提示upstream timed out (110: Connection timed out) while reading response header from upstream,连接超时,这里的连接超时是nginx和uWSGI连接超时。

nginx error.log

我们打开nginx的配置文件,在location下添加如下配置:

proxy_read_timeout 300;  # 指定接收uWSGI应答的超时时间,完成握手后接收uWSGI应答的超时时间。

proxy_send_timeout 300; # 指定向uWSGI传送请求的超时时间,完成握手后向uWSGI传送请求的超时时间。

proxy_connect_timeout 300; # 指定连接到后端uWSGI的超时时间。

如图:

nginx配置

注意,这里我用的是http协议,如果使用的是uwsgi协议,则相应的配置为:

proxy_read_timeout 300;  # 指定接收uWSGI应答的超时时间,完成握手后接收uWSGI应答的超时时间。

uwsgi_send_timeout 300; # 指定向uWSGI传送请求的超时时间,完成握手后向uWSGI传送请求的超时时间。

proxy_connect_timeout 300; # 指定连接到后端uWSGI的超时时间。

修改完重启nginx,再次访问接口,发现这是nginx报502,error.log显示:upstream prematurely closed connection while reading response header from upstream。我们可以看出来,是上游关闭导致nginx报错,也就是uWSGI服务器超时丢弃。

nginx error.log

这里去google查了一下,在uwsgi.ini或启动命令中添加 harakiri参数,设置超时时间,但我设置了 --harakiri 300 后没有任何效果。后来才想起来,由于我使用的是http协议,harahkiri貌似不生效,改为--http-timeout 300 后解决。


command=/usr/bin/uwsgi --uid www-data --gid www-data --http 127.0.0.1:5001 --wsgi-file app.py --callable app --master --processes 2 --threads 16 --http-timeout 300

environment=FLASK_ENV=stag

directory=/home/wape/01

stdout_logfile=/var/log/supervisor/%(program_name)s.log

stdout_logfile_maxbytes=50MB

stdout_logfile_backups=10

stderr_logfile=/var/log/supervisor/%(program_name)s.log

stderr_logfile_maxbytes=50MB

stderr_logfile_backups=10

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容