上一篇讲到了通过“动静分离”来优化了js/css等静态文件的加载效率,也提到了Gunicorn来部署Django代码。所以,本文就讲一下使用nginx+gunicorn+django这种方式来部署Django系统,使之可以实现服务器端多进程处理,从而答复提高服务器端处理能力。
Gunicorn的配置文件为(gunicorn.cfg):
# gunicorn cmd: gunicorn aew.wsgi -c gunicorn.cfgimport multiprocessingbind = "unix:/home/qa/gunicorn.sock"pidfile = "/home/qa/gunicorn.pid"workers = multiprocessing.cpu_count() * 2 + 1threads = multiprocessing.cpu_count()max_requests = 1000reload = Trueloglevel = "info"accesslog = "access.log"errorlog = "error.log"daemon = True
我的应用是Django应用,用Gunicorn启动的命令为:gunicorn aew.wsgi -c gunicorn.cfg
根据前面的配置,我使用的是Unix Domain Sockect,所以在Nginx与Gunicorn通信的方式就是Unix Domain Sockect;Nginx的一些相关配置改动为(见:https://github.com/smilejay/other-code/blob/master/config/nginx-gunicorn.diff ):
diff --git a/nginx.conf b/nginx.confindex ed521ca..933df53 100644--- a/nginx.conf+++ b/nginx.conf@@ -42,9 +42,13 @@ http { # for more information. include /etc/nginx/conf.d/*.conf;+ upstream aew_server {+ server unix:/home/qa/gunicorn.sock max_fails=10 fail_timeout=10s;+ }+ server { listen 80 default_server; server_name _; root /usr/share/nginx/html; #charset koi8-r;@@ -54,7 +58,17 @@ http { # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf;+ location /static {+ autoindex on;+ alias /home/qa/aew/static;+ break;+ }+ location / {+ if ( !-f $request_filename ) {+ proxy_pass http://aew_server;+ break;+ }
这里的Nginx作为反向代理,需要配置一些东西,遇到过一个问题,见:Nginx+Gunicorn+Django出现“Bad Request (400)”
经过Nginx+Gunicorn的配置之后,我对以前写过过的一个API做了一下性能对比测试实验(Gunicorn 和 django的runserver启动的服务作对比),实验结果非常的不错:使用了5个、10个、20个并发进行测试,响应时间缩短为原来的0.3倍左右;吞吐量(TPS)为原来的3~10倍。具体对比数据如下图: