Nginx+Uwsgi部署Django程序

原来使用apache进行部署,感觉内存占用大以及速度比较慢就换成了nginx+uwsgi的方式,结果完爆apache啊!

首先安装nginx以及uwsgi:

yum install nginx
pip install uwsgi

然后编辑uwsgi的配置文件,这里我使用ini文件格式,示例如下:

[uwsgi]
socket = 127.0.0.1:9000
chdir = /var/www/html/test
pidfile = /var/run/db_uwsgi.pid
daemonize = /var/log/db_uwsgi.log
wsgi-file = /var/www/html/test/wsgi.py
processes = 4
threads = 2
stats = 127.0.0.1:9191

根据实际情况修改程序目录、进程、线程,还有更高级的配置选项细节看uwsgi的文档。

启动:uwsgi ini路径

停止:uwsgi –stop pidfile路径

重起:uwsgi –reload pidfile路径

nginx配置示例如下:

server {
        listen  800;
        server_name     192.168.2.42 ;
        access_log      /var/log/nginx-dc-access_log;
        error_log       /var/log/nginx-dc-error.log;
        charset         utf-8;
        default_type    text/html;
        proxy_set_header  Host      $host;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For $remote_addr;
        set_real_ip_from   192.168.2.0/24;
        set_real_ip_from   192.168.2.42;
        real_ip_header     X-Real-IP;
        location / {
                uwsgi_pass 127.0.0.1:9000;
                include uwsgi_params;
        }
        location /static {
                root /var/www/html/test;
        }
     }

更多高级配置请看nginx文档。

配置完成后启动nginx以及uwsgi即可:

service nginx start
uwsgi test.ini
[uWSGI] getting INI configuration from test.ini

如果你需要使用脚本方式进行uwsgi的重启,记得stop后sleep3秒钟左右再启动,否则重启不一定成功。

echo "stop uwsgi"
uwsgi --stop /var/run/db_uwsgi.pid
echo "wait 5's"
sleep 5
uwsgi /var/www/html/test/test.ini
echo "start uwsgi"