温馨提示×

Debian如何配置Python服务

小樊
44
2026-07-05 22:52:06
栏目: 编程语言

在 Debian 上配置 Python 服务(后台服务),常见且推荐的方式是使用 systemd。下面按从简单到规范的方式说明,适用于 Debian 10/11/12。


一、准备 Python 服务程序

假设你的 Python 服务是一个长期运行的脚本,例如:

# /opt/myservice/app.py
import time

while True:
    print("Service is running...")
    time.sleep(5)

✅ 建议:

  • 使用 虚拟环境(venv)
  • 使用 Python 3
  • 程序路径固定,例如 /opt/myservice

二、创建 systemd 服务(推荐方式)

1️⃣ 创建 systemd 服务文件

sudo nano /etc/systemd/system/myservice.service

示例内容(✅ 非常重要):

[Unit]
Description=My Python Service
After=network.target

[Service]
Type=simple
User=myuser
WorkingDirectory=/opt/myservice
ExecStart=/opt/myservice/venv/bin/python /opt/myservice/app.py
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

参数说明

参数 说明
Type=simple 普通脚本
User 非 root 用户(安全)
Restart=always 崩溃自动重启
After=network.target 网络启动后再启动

2️⃣ 重新加载 systemd

sudo systemctl daemon-reload

3️⃣ 启动并设置开机自启

sudo systemctl start myservice
sudo systemctl enable myservice

4️⃣ 查看状态与日志

systemctl status myservice
journalctl -u myservice -f

三、使用虚拟环境(强烈推荐)

cd /opt/myservice
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

ExecStart 使用:

ExecStart=/opt/myservice/venv/bin/python /opt/myservice/app.py

四、如果 Python 服务是 Web 服务(Flask / FastAPI)

示例(Flask)

ExecStart=/opt/myservice/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app

然后配合 Nginx 反向代理(生产环境标准做法)。


五、常见问题排查

❌ 服务启动失败

journalctl -u myservice --no-pager

❌ 权限问题

sudo chown -R myuser:myuser /opt/myservice

❌ Python 路径错误

确认:

which python3
/opt/myservice/venv/bin/python --version

六、开发阶段快速方式(不推荐生产)

nohup python3 app.py > output.log 2>&1 &

七、总结(推荐方案)

生产环境标准做法

  • Python + venv
  • systemd 管理服务
  • journalctl 查看日志
  • 非 root 用户运行

如果你愿意,可以告诉我:

  • Python 版本
  • 是否是 Web 服务
  • 是否需要开机自启 / 自动重启
  • Debian 具体版本

我可以帮你写 完全可用的服务文件

0