在 Ubuntu 上配置 Python 服务,常见场景有系统服务(开机自启)、Web 服务部署、虚拟环境管理等。下面我按最常见、最实用的方式来给你讲,你可以按需取用。
Ubuntu 一般自带 Python3:
python3 --version
如未安装:
sudo apt update
sudo apt install python3 python3-pip python3-venv -y
适合:后台运行脚本 / API 服务 / 定时任务
mkdir -p /opt/myservice
vim /opt/myservice/app.py
示例 app.py:
import time
while True:
print("running...")
time.sleep(5)
sudo vim /etc/systemd/system/myservice.service
内容示例:
[Unit]
Description=My Python Service
After=network.target
[Service]
User=ubuntu
WorkingDirectory=/opt/myservice
ExecStart=/usr/bin/python3 /opt/myservice/app.py
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable myservice
sudo systemctl start myservice
systemctl status myservice
journalctl -u myservice -f
避免依赖冲突:
cd /opt/myservice
python3 -m venv venv
source venv/bin/activate
pip install flask
修改 ExecStart:
ExecStart=/opt/myservice/venv/bin/python /opt/myservice/app.py
pip install gunicorn
myservice.service 示例:
ExecStart=/opt/myservice/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app
sudo apt install nginx
Nginx 配置:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
sudo nginx -t
sudo systemctl restart nginx
crontab -e
示例(每分钟执行):
* * * * * /opt/myservice/venv/bin/python /opt/myservice/app.py
root 跑业务服务在 service 中加:
Environment=ENV=production
Restart=on-failure
我可以直接给你一份可复制的完整配置。