在 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
假设:
/opt/myservice/app.py/opt/myservice/venvsudo 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
sudo systemctl daemon-reexec
sudo systemctl enable myservice
sudo systemctl start myservice
systemctl status myservice
journalctl -u myservice -f
pip install gunicorn
systemd 示例:
ExecStart=/opt/myservice/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app
nginx → gunicorn → python app
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
python 而不是 python3Restart=always如果你能告诉我:
我可以直接给你一套可用的配置文件。