使用Gunicorn部署Django
Gunicorn和uwsgi一样,也是一个服务器,是一个轻量服务器,所以使用起来简洁,好像现在都在用这种方式部署了。
一、安装
pip install gunicorn
二、简单测试
gunicorn myproject.wsgi -b 0.0.0.0:8080
三、正式使用
1. 编写 systemctl (compass.service)服务启动 gunicorn
[Unit]
Description=Gunicorn daemon for Django project
After=network.target
[Service]
WorkingDirectory=/opt/hy/compass
Environment="PATH=/opt/hy/venv/bin"
ExecStart=/opt/hy/venv/bin/gunicorn --workers 4 --bind unix:/opt/hy/compass/compass.sock compass.wsgi:application
[Install]
WantedBy=multi-user.target
compass.service 放在 /etc/systemd/system/compass.service
重新加载 systemd 配置:sudo systemctl daemon-reload
启动 Gunicorn 服务:sudo systemctl start gunicorn
设置 Gunicorn 开机自启: sudo systemctl enable gunicorn
2. 编写nginx配置
server {
listen 8002;
server_name _;
charset utf-8;
client_max_body_size 75M;
location / {
include proxy_params;
proxy_pass http://unix:/opt/hy/compass/compass.sock;
}
}
nginx -s reload && nginx -s reopen,然后后端服务就可以正常访问了
四、异常问题处理
# 问题一:/opt/hy/compass/compass.sock 这个文件是怎么来的
systemctl服务启动后,会运行gunicorn,这个时候gunicorn会自动创建出xx.sock这个文件
# 问题二:compass.service服务启动失败,报错:[69888] [ERROR] Can't connect to /opt/hy/compass/compass.sock
1.检查 xx.sock 文件是否存在,如果不存在应该是权限问题
sudo chown -R username /opt/hy/compass
sudo chmod 755 /opt/hy/compass
遇到问题不要怕,一项一项的检查
1.先使用 manage.py 看看能不能正常访问
2.在测试gunicorn有没有问题
3.在测试 systemctl 服务,有没有创建 sock 文件,服务状态是否正常
4. 在检查nginx


浙公网安备 33010602011771号