django项目,使用nginx和gunicorn部署守护进程

Administrator
发布于 2025-05-31 / 4 阅读
0
0

django项目,使用nginx和gunicorn部署守护进程

✅ 一、准备工作

1. 安装依赖(假设你已经有 Python 和 pip)

pip install gunicorn

2. 假设你的 Django 项目结构如下:

/home/youruser/yourproject/
├── manage.py
├── yourproject/
│   ├── settings.py
│   └── ...

✅ 二、使用 Gunicorn 启动守护进程

在项目根目录(有 manage.py 的地方)执行:

gunicorn yourproject.wsgi:application \
    --bind 127.0.0.1:8001 \
    --workers 3 \
    --daemon \
    --pid /run/gunicorn.pid \
    --access-logfile /var/log/gunicorn/access.log \
    --error-logfile /var/log/gunicorn/error.log

解释:

  • --bind 127.0.0.1:8001:Gunicorn 监听本地端口

  • --daemon:以守护进程运行

  • --pid:指定 PID 文件

  • --logfile:指定日志文件

建议把这个命令写进一个脚本 start_gunicorn.sh,便于管理。


✅ 三、配置 Nginx 作为反向代理

编辑配置文件:

sudo vim /etc/nginx/conf.d/yourproject.conf

内容如下:

server {
    listen 80;
    server_name yourdomain.com;
​
    location / {
        proxy_pass http://127.0.0.1:8001;
        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 /home/youruser/yourproject/static/;
    }
​
    location /media/ {
        alias /home/youruser/yourproject/media/;
    }
}

重启 Nginx

sudo nginx -t && sudo systemctl reload nginx

✅ 四、收集静态资源

python manage.py collectstatic

✅ 五、可选:使用 systemd 管理 Gunicorn(推荐)

创建服务文件:

sudo vim /etc/systemd/system/gunicorn.service

内容如下:

[Unit]
Description=gunicorn daemon
After=network.target
​
[Service]
User=youruser
Group=www-data
WorkingDirectory=/home/youruser/yourproject
ExecStart=/usr/local/bin/gunicorn --workers 3 --bind 127.0.0.1:8001 yourproject.wsgi:application
​
[Install]
WantedBy=multi-user.target

启动并开机自启

sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl start gunicorn
sudo systemctl enable gunicorn

✅ 六、检查部署状态

curl http://127.0.0.1:8001     # 检查 Gunicorn 是否响应
curl http://yourdomain.com     # 检查 Nginx 是否代理成功



评论