温馨提示×

ubuntu python服务怎么配置

小樊
44
2026-10-25 00:12:23
栏目: 编程语言

在 Ubuntu 上配置 Python 服务,常见场景有系统服务(开机自启)、Web 服务部署、虚拟环境管理等。下面我按最常见、最实用的方式来给你讲,你可以按需取用。


一、基础准备(必做)

1. 安装 Python

Ubuntu 一般自带 Python3:

python3 --version

如未安装:

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

二、使用 systemd 配置 Python 服务(推荐)

适合:后台运行脚本 / API 服务 / 定时任务

示例:运行一个 Python 脚本作为服务

1. 准备脚本

mkdir -p /opt/myservice
vim /opt/myservice/app.py

示例 app.py:

import time

while True:
    print("running...")
    time.sleep(5)

2. 创建 systemd 服务文件

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

3. 启动服务

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

4. 查看状态

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

四、部署 Python Web 服务(Flask / FastAPI)

方式 1:Gunicorn + systemd(最常用)

pip install gunicorn

myservice.service 示例:

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

方式 2:Nginx + Gunicorn(生产推荐)

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

六、常见问题

1. 权限问题

  • 不要用 root 跑业务服务
  • 日志目录要有写权限

2. 环境变量

在 service 中加:

Environment=ENV=production

3. 服务不重启

Restart=on-failure

七、你可以告诉我:

  • 是 脚本 / API / Web 项目?
  • 是否需要 开机自启?
  • 是否用 Flask / Django / FastAPI?
  • Ubuntu 版本(20.04 / 22.04 / 24.04)?

我可以直接给你一份可复制的完整配置。

0 踩