Linux部署python项目为服务,开启自启动
在 Linux 系统中将 Python 项目部署为服务并设置开机自启动,可以通过 Systemd(现代 Linux 发行版的标准服务管理工具)。以下是详细方法:
Systemd 是大多数 Linux 发行版(如 Ubuntu、Debian、CentOS)的默认服务管理器,适合管理后台服务。
步骤 1:创建 Systemd 服务文件
1.创建一个服务配置文件(如 my_python_service.service
):
sudo nano /etc/systemd/system/my_python_service.service
2.写入以下内容(根据实际情况修改):
[Unit]
Description=My Python Service
After=network.target[Service]
User=root # 可以改为普通用户(如 `ubuntu`)
WorkingDirectory=/path/to/your/project # Python 项目目录
ExecStart=/usr/bin/python3 /path/to/your_script.py # Python 解释器 + 脚本路径
Restart=always # 崩溃后自动重启
RestartSec=5 # 重启间隔(秒)
Environment="PYTHONUNBUFFERED=1" # 避免日志缓冲[Install]
WantedBy=multi-user.target # 多用户模式启动
步骤 2:启用并启动服务
# 重新加载 Systemd 配置
sudo systemctl daemon-reload# 启动服务
sudo systemctl start my_python_service# 设置开机自启动
sudo systemctl enable my_python_service
步骤 3:检查服务状态
# 查看服务状态
sudo systemctl status my_python_service# 查看日志
journalctl -u my_python_service -f
常用命令
命令 | 作用 |
---|---|
sudo systemctl start my_python_service | 启动服务 |
sudo systemctl stop my_python_service | 停止服务 |
sudo systemctl restart my_python_service | 重启服务 |
sudo systemctl disable my_python_service | 禁用开机自启动 |