安装环境介绍:
python2.7.10
django1.7.9
linux CentOS release 6.5 (Final) 64
假设我的项目位置为/var/www/myweb
服务器IP为192.168.0.100
1、插件安装
gunicorn-19.7.1 uwsgi组件
gevent-1.2.1 异步组件
greenlet-0.4.12 异步组件
supervisor-3.3.0 进程管理组件
直接下载然后运行 对应的 python setup.py install
2、myweb wsgi 配置
位置: /var/www/myweb/wsgi.py
import sys
import os
p = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.split(p)[0])
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
3、运行 gunicorn
cd /var/www/myweb
/usr/local/python/bin/gunicorn -w 4 -k gevent -m 0002 -b 0.0.0.0:8000 --error-logfile /var/log/gunicorn/myweb_gunicorn_error.log wsgi:application
-w 启动多少个工作进程,可以根据CPU的个数开启,一个CPU开一个
-k 工作进程类
-m umask权限
-b 地址端口配置
wsgi:application wsgi实例
对于直接运用gunicorn不通过supervisor的话,可以守护的方式启动,加入参数 -D
/usr/local/python/bin/gunicorn -w 4 -k gevent -m 0002 -b 0.0.0.0:8000 --error-logfile /var/log/gunicorn/myweb_gunicorn_error.log -D wsgi:application
可以通过 gunicorn -h 查看更多配置参数
确保8000端口,防火墙已经开启
通过 http://192.168.0.100:8000 访问
4、nginx的安装与配置
为了提高网站的效率,对于静态文件通过nginx发送,
其他应用URL转发到gunicorn启动的进程
安装:
./configure
make
make install
配置:
server {
listen 8080;
location / {
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
server_name_in_redirect off;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 300m;
proxy_pass http://127.0.0.1:8000;
}
location /media/ {
alias /var/www/myweb/static/;
}
location /static/ {
alias /var/www/myweb/static/;
}
}
sudo /usr/local/nginx/sbin/nginx -s reload
确保8080端口,防火墙已经开启
通过 http://192.168.0.100:8080 访问
5、 supervisor 方式部署gunicorn
守护方式运行,也为了后续维护,
比如修改参数,启动,停止等,supervisor都非常方便
/etc/supervisor/conf.d 下新增 gunicorn.conf
[program:myweb_gunicorn]
directory=/var/www/myweb
command=/usr/local/python/bin/gunicorn -w 4 -k gevent -m 0002 -b 0.0.0.0:8000 --error-logfile /var/log/gunicorn/myweb_gunicorn_error.log wsgi:application
autostart = true
startsecs = 5
user=myuser
redirect_stderr = true
stdout_logfile_maxbytes = 20MB
stdout_logfile_backups = 20
stdout_logfile =/var/log/gunicorn/myweb_gunicorn.log
特备注意,改了gunicorn.conf一定要重新加载配置,否则重启不生效
/usr/local/python/bin/supervisorctl reload myweb_gunicorn
#重启服务
/usr/local/python/bin/supervisorctl restart myweb_gunicorn
6、linux配置其他用户sudo权限启动
vim /etc/sudoers
myuser ALL=(ALL) NOPASSWD: /usr/local/nginx/sbin/nginx