You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 20服务器搭配Gunicorn和Nginx时如何重启/重载Django

解决Django+Gunicorn+Nginx部署的两个核心问题

一、修改Django配置后快速生效,告别繁琐操作

修改ALLOWED_HOSTS这类Django配置后,完全不需要重启服务器、折腾虚拟环境,也不用反复启停Nginx。你只需要针对性操作:

  • 重启Gunicorn:因为Django的配置是由Gunicorn加载的,只有重启它才能读取更新后的settings文件
  • 仅当修改Nginx配置时重载Nginx:如果没碰过Nginx的配置文件,这一步可以直接跳过

用systemd管理Gunicorn,一键操作

把Gunicorn注册成systemd服务,不用进入虚拟环境就能直接控制:

  1. 创建服务文件:sudo nano /etc/systemd/system/gunicorn.service
  2. 写入以下配置(替换成你的实际路径):
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=你的服务器用户名
Group=www-data
WorkingDirectory=/path/to/your/django/project
ExecStart=/path/to/your/venv/bin/gunicorn --workers 3 --bind unix:/path/to/your/django/project/myproject.sock myproject.wsgi:application

[Install]
WantedBy=multi-user.target
  1. 重载systemd配置:sudo systemctl daemon-reload
  2. 设置开机自启:sudo systemctl enable gunicorn

之后修改Django配置,只需要执行:

  • 重启Gunicorn:sudo systemctl restart gunicorn
  • 若修改过Nginx配置:sudo systemctl reload nginx

二、Gunicorn与Nginx的正确协同启动方式

通过systemd管理Gunicorn,配合Nginx的系统服务,就能实现开机自动协同启动,日常管理也更简单:

  1. 确保Gunicorn已通过上面的步骤注册为systemd服务并开启开机自启
  2. Nginx默认是Ubuntu的系统服务,直接设置开机自启:sudo systemctl enable nginx

这样开机时,systemd会按顺序启动网络服务→Gunicorn→Nginx,完全无需手动干预。日常启停只用以下命令:

  • 启动/停止Gunicorn:sudo systemctl start gunicorn / sudo systemctl stop gunicorn
  • 启动/停止Nginx:sudo systemctl start nginx / sudo systemctl stop nginx

关键权限注意

Gunicorn绑定的socket文件(如示例中的myproject.sock)要确保Nginx能访问:

  • 保持服务配置里的Group=www-data
  • 给项目目录设置合适权限:sudo chmod 775 /path/to/your/django/project

内容的提问来源于stack exchange,提问作者Andy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:52:11