配置Django和UWSGI开机启动
日期: 2024-02-03 | 作者: admin | 浏览: 112

配置Django和UWSGI开机启动

1. 编写UWSGI配置文件,并保存为uwsgi.ini
[uwsgi]
uid = www-data
gid = www-data

# 注意:需安装相应文件 sudo apt install uwsgi-plugin-python3
plugins = /usr/lib/uwsgi/plugins/python3
# plugins   = python3
# Django-related settings  

# the base directory (full path)  
chdir     = /var/www/project
# Django's wsgi file  
module    = project.wsgi

# wsgi-file = /var/www/project/project/wsgi.py
pidfile   = /etc/uwsgi/project.pid

# the virtualenv (full path)  
home      = /var/work_env/project_env

# process-related settings  
# master  
master    = true
# maximum number of worker processes  
processes = 3 

# the socket (use the full path to be safe  
socket    = 127.0.0.1:9090
# socket = /var/www/project/project.sock

# ... with appropriate permissions - may be needed  
# chmod-socket    = 664  
# clear environment on exit  
vacuum    = true
daemonize = /tmp/project_uwsgi.log

log-maxsize = 100000
disable-logging = true
2. 编写启动脚本,并保存为start.sh,注意脚本存放位置
#! bin/bash -e
/usr/bin/uwsgi --ini /var/www/project/uwsgi.ini
3. 为脚本添加执行权限
chmod +x start.sh
4. 配置开机启动
4.1 有/etc/rc.local文件,直接在该文件里增加启动项目即可
# vim /etc/rc.local
/srv/var/project/start.sh > /tmp/uwsgi.log 2>&1
4.2 没有/etc/rc.local文件,需要配置开机启动服务
# 1.新增服务配置文件
# vim /etc/systemd/system/my_service.service

# 2.编辑配置文件
[Unit]
Description=My custom startup script
 
[Service]
Type=simple
# 确保文件路径正确
ExecStart=/path/to/your/script.sh
 
[Install]
WantedBy=multi-user.target

# 3.保存并重载管理器配置
sudo systemctl daemon-reload

# 4. 添加服务自启动
systemctl enable my_service.service
5. 补充说明

UWSGI 服务开机正常,一会就挂掉问题!

解决方案:删除uwsgi配置文件中设置日志用的daemonize!!,可以更换为 logto = /path/to/your/logfile.log

网上找的说明:
当您从uwsgi配置中删除daemonize选项后,uwsgi不再以守护进程的形式运行,而是在前台运行。
这意味着uwsgi的标准输出和错误直接连接到了启动它的进程。在您使用systemd启动uwsgi的情况下,systemd会捕获这些输出,并可以使用journalctl来查看。

使用daemonize时,uwsgi尝试在后台运行并将其输出重定向到您指定的日志文件。
这可能与systemd的预期行为产生了冲突。可能的是,当uwsgi尝试后台运行时,systemd误认为uwsgi主进程已经完成并尝试关闭服务,从而导致上述的停止和超时问题。一般来说,当使用systemd管理服务时,最佳做法是让服务在前台运行并让systemd处理日志和服务的生命周期。

如果您希望继续将uwsgi的日志记录到指定的文件中,而不是让systemd通过journalctl来管理,您可以使用uwsgi的logto选项而不是daemonize。