温馨提示×

debian python服务怎么起

小樊
67
2026-09-05 06:22:57
栏目: 编程语言

在 Debian 上启动 Python 服务,常见有几种方式,取决于你是临时跑一下、开机自启,还是生产环境稳定运行。下面按常见场景给你说明。


一、最简单:直接运行(测试用)

python3 your_script.py

或(有虚拟环境时):

source venv/bin/activate
python your_script.py

⚠️ 关闭终端就会停止,不适合生产。


二、后台运行(不推荐长期使用)

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

查看进程:

ps aux | grep python

三、systemd 方式(✅ 推荐,Debian 官方方式)

1. 准备 Python 脚本

假设:

  • 脚本路径:/opt/myservice/app.py
  • 用虚拟环境:/opt/myservice/venv

2. 创建 systemd 服务文件

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

示例内容:

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

[Service]
User=www-data
WorkingDirectory=/opt/myservice
ExecStart=/opt/myservice/venv/bin/python app.py
Restart=always

[Install]
WantedBy=multi-user.target

3. 启动服务

sudo systemctl daemon-reexec
sudo systemctl enable myservice
sudo systemctl start myservice

4. 查看状态 / 日志

systemctl status myservice
journalctl -u myservice -f

四、Web 服务(Flask / FastAPI 等)

方式 1:gunicorn + systemd(✅ 推荐)

pip install gunicorn

systemd 示例:

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

方式 2:nginx + gunicorn(生产标准)

nginx → gunicorn → python app

五、Docker(可选,更现代)

FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]

六、常见坑

  • ❌ 用 python 而不是 python3
  • ❌ 没写绝对路径
  • ❌ 权限不足(User 配置错误)
  • ❌ 程序异常退出但没 Restart=always

如果你能告诉我:

  • Python 版本
  • 是否是 Web 服务
  • 是否要开机自启

我可以直接给你一套可用的配置文件。

0 踩