在 Ubuntu 上部署 Python 服务有多种方式,下面从简单到生产级给你一套常见方案和步骤。
python3 app.py
缺点:退出终端就停止,不适合生产。
sudo apt update
sudo apt install python3 python3-pip python3-venv
mkdir /opt/myservice
cd /opt/myservice
python3 -m venv venv
source venv/bin/activate
pip install flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello Ubuntu"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
sudo nano /etc/systemd/system/myservice.service
内容:
[Unit]
Description=My Python Service
After=network.target
[Service]
User=ubuntu
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
pip install gunicorn
sudo apt install nginx
gunicorn -w 4 -b 127.0.0.1:8000 app:app
sudo nano /etc/nginx/sites-available/myservice
server {
listen 80;
server_name your_domain;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
sudo ln -s /etc/nginx/sites-available/myservice /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
docker build -t myservice .
docker run -d -p 8000:8000 myservice
nohup python3 app.py &
cron 或 systemd timer如果你告诉我:
我可以给你更精确的部署方案。