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

修改Django代码后无需重启Linux,Gunicorn Systemd服务不识别变更怎么办?

问题描述

在Ubuntu上用systemd部署Django应用,按教程创建了gunicorn.socket和gunicorn.service文件,但修改Python代码后必须重启电脑才能看到变更。尝试以下命令组合均无效:

systemctl daemon-reload
systemctl restart gunicorn.service
systemctl restart gunicorn.socket

报错信息:

Failed to restart gunicorn.service: Unit gunicorn.socket not found.

但gunicorn.socket文件实际存在。

相关配置片段

Nginx配置

location /static/ {
    root /root/djdeploy/demo/static;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}

gunicorn.socket 文件内容

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

gunicorn.service 文件内容

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=nad
Group=www-data
WorkingDirectory=/home/nad/djdeploy/demo
ExecStart=/home/nad/djdeploy/venv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          demo.wsgi:application

[Install]
WantedBy=multi-user.target
解决方法

1. 先修复socket单元未识别问题

报错说明systemd没找到gunicorn.socket单元,原因主要有两个:

  • 文件路径错误:systemd单元文件必须放在/etc/systemd/system/或/usr/lib/systemd/system/目录下,检查你的两个文件是不是放在了其他路径。如果是,移到/etc/systemd/system/下,或者执行命令时用绝对路径指定。
  • 文件名拼写错误:确认文件名是gunicorn.socket,全小写、无空格或特殊字符。

2. 重新加载配置并重启服务

路径确认正确后,执行以下命令:

# 重新加载systemd配置,让单元文件生效
sudo systemctl daemon-reload
# 启用并立即启动socket单元(第一次配置时需要)
sudo systemctl enable --now gunicorn.socket
# 重启gunicorn服务,强制加载新代码
sudo systemctl restart gunicorn.service

3. 验证服务状态

执行命令检查服务是否正常运行:

sudo systemctl status gunicorn.service
sudo systemctl status gunicorn.socket

如果服务启动失败,查看实时日志排查问题:

journalctl -u gunicorn.service -f

4. 代码变更生效的核心逻辑

gunicorn会把Python代码预加载到内存,修改代码后必须重启gunicorn服务才能让新代码生效,完全不需要重启系统。之前的问题根源是socket单元没被systemd识别,导致无法正常触发服务重启。

额外注意:

  • 静态文件变更后,先执行python manage.py collectstatic,再重启Nginx:sudo systemctl restart nginx。
  • 确认/run/gunicorn.sock的权限,你的配置里已经设置gunicorn运行用户nad属于www-data组,Nginx用户(www-data)有权限访问该socket,这部分没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:11:22