centos7下通过nginx+gunicorn部署django应用笔记
1.安装基础环境启动gunicorn
新建虚拟环境imooc并切换到imooc
pip install django==2.0 gunicorn
django-admin startproject imooc
cd imooc
命令行启动
gunicorn imooc.wsgi:application -w 2 -b 127.0.0.1:8000
imooc.wsgi:application imooc是你django工程的名称,后面不用改
-w --workers 意思是要启动的进程数量
-b --bind 绑定的IP地址和端口
-k --worker-class 启动的worker类型(gthread,sync,eventlet,gevent,tornado),默认是同步阻塞方式启动
访问:127.0.0.1:8000
以配置文件启动:
gunicorn imooc.wsgi:application -k gthread -c ~/projects/imooc/conf/gunicorn.conf.py
# gunicorn.conf.py
import multiprocessing
bind = "127.0.0.1:8888"
workers = 2
errorlog = ' ~/projects/imooc/log/error.log'
accesslog = ' ~/projects/imooc/log/access.log'
#loglevel = 'info'
loglevel = 'error'
2.收集静态文件
1 | # imooc settings.py |
运行 python manage.py collectstatic
运行gunicorn
gunicorn imooc.wsgi:application -k gthread -c ~/projects/imooc/conf/gunicorn.conf.py
3.安装并启动nginx
1.安装nginx和开放http服务与端口
https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-centos-7
systemctl start nginx 访问设备IP出现欢迎界面
systemctl enable nginx 设置nginx自启动
2.新建gunicorn.nginx.conf
vim ~/projects/imooc/conf/gunicorn.nginx.conf
# gunicorn.nginx.conf
server {
# the port your site will be served on
listen 8080;
# the domain name it will serve for
server_name 设备IP地址; # 设备IP地址或者绑定的域名
charset utf-8;
location / {
proxy_pass http://127.0.0.1:8000;#gunicorn绑定的地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static {
alias ~/projects/imooc/static; # your Django project's static files - amend as required
}
}
3.建立软连接
touch /etc/nginx/conf.d/(不存在再创建)
ln -s ~/projects/imooc/conf/gunicorn.nginx.conf /etc/nginx/conf.d/
4.修改/etc/nginx/nginx.conf并启动nginx
http{...}添加如下一行:
include /etc/nginx/conf.d/*.conf;
并修改用户为服务器当前登录用户
sudo /usr/sbin/nginx -t
systemctl restart nginx