温馨提示×

怎样用Debian配Python服务

小樊
48
2026-10-05 03:06:02
栏目: 编程语言

下面按最常见场景给你一个清晰、可落地的 Debian 上配置 Python 服务的方法。假设你用的是 Debian 11/12,Python 服务是一个普通脚本或 Web 服务(如 FastAPI / Flask)。


一、基础环境准备

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装 Python

Debian 一般自带 Python3:

python3 --version

如果没有:

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

二、推荐方式:用 systemd 管理 Python 服务(最标准)

1. 创建项目目录

sudo mkdir -p /opt/myservice
sudo chown $USER:$USER /opt/myservice
cd /opt/myservice

2. 创建虚拟环境

python3 -m venv venv
source venv/bin/activate
pip install flask  # 示例

3. 写一个简单的 Python 服务

app.py:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello from Debian Python service"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

三、配置 systemd 服务

1. 创建 service 文件

sudo 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 /opt/myservice/app.py
Restart=always
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target

⚠️ User 可用你的用户名,或专门建一个系统用户


2. 启动服务

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

3. 查看状态

sudo systemctl status myservice
journalctl -u myservice -f

四、对外访问(可选)

用 Nginx 反向代理(推荐)

sudo apt install nginx -y
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
    }
}
sudo nginx -t
sudo systemctl reload nginx

五、常见变体

✅ FastAPI 服务

pip install fastapi uvicorn
ExecStart=/opt/myservice/venv/bin/uvicorn app:app --host 0.0.0.0 --port 8000

✅ 后台脚本(非 Web)

while True:
    do_something()
    time.sleep(10)

六、调试 checklist

  • ✅ python app.py 本地能跑
  • ✅ 虚拟环境路径正确
  • ✅ 用户有目录权限
  • ✅ 端口未被占用

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

  • Python 版本(3.9 / 3.11?)
  • 是 Web 服务还是后台任务?
  • Debian 版本

我可以直接给你一份可直接用的 service 文件。

0 踩