温馨提示×

ubuntu如何部署python服务

小樊
44
2026-09-13 11:45:29
栏目: 编程语言

在 Ubuntu 上部署 Python 服务有多种方式,下面从最简单到生产级逐步介绍,你可以按需求选择。


一、最基础方式(适合测试 / 临时运行)

1. 安装 Python

sudo apt update
sudo apt install python3 python3-pip -y

2. 运行 Python 脚本

python3 app.py

⚠️ 缺点:关闭终端即停止


二、使用 nohup(简单后台运行)

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

查看日志:

tail -f app.log

三、使用 systemd(推荐 ✅ 生产常用)

1. 准备服务文件

假设你的服务:

  • 路径:/opt/myservice/app.py
  • 用户:ubuntu
sudo nano /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

2. 启动服务

sudo systemctl daemon-reload
sudo systemctl start myservice
sudo systemctl enable myservice

3. 查看状态

sudo systemctl status myservice

四、使用虚拟环境(推荐 ✅)

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

修改 systemd:

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

五、Web 服务部署(Flask / FastAPI)

1. 安装 Gunicorn

pip install gunicorn

2. 启动示例

gunicorn -w 4 -b 0.0.0.0:8000 app:app

3. systemd + Gunicorn

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

六、配合 Nginx(生产推荐 ✅)

sudo apt install nginx

Nginx 配置示例:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
    }
}
sudo systemctl restart nginx

七、Docker 部署(现代化 ✅)

FROM python:3.11
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
长期运行 systemd
Web 服务 Gunicorn + Nginx
微服务 Docker

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

  • Python 服务类型(脚本 / Flask / FastAPI / 爬虫)
  • 是否要对外网访问
  • Ubuntu 版本

我可以给你完整可直接用的配置

0