ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Linux部署Python服务

2026/8/7 10:54:01 拓冰建站 浏览量
Linux部署Python服务

1、创建项目目录与虚拟环境

#确保安装 Python 和 python3-venv 工具
sudo apt update
sudo apt install python3 python3-pip python3-venvmkdir myproject
cd myproject
python3 -m venv venv  # 创建虚拟环境#Linux
source venv/bin/activate  # 激活虚拟环境#Windowds
venv\Scripts\activate   # 激活虚拟环境

2、安装依赖库

#研发环境导出依赖文件
pip freeze > requirements.txt#依赖安装
pip install -r requirements.txt#验证安装成功
pip freeze

接下来可以使用 systemd 或 Supervisor 来管理 Python 程序。 

3、使用 systemd 管理程序

3.1、创建 systemd 服务文件

vi /etc/systemd/system/myapp.service[Unit]
Description=IRS Python Application    #服务的描述
After=network.target      #确保服务在网络可用后启动[Service]
User=root   #指定哪个用户运行该程序。通常推荐创建一个专用的用户运行服务。
WorkingDirectory=/data/irs   #设置 Python 程序所在的目录
ExecStart=/data/irs/venv/bin/python /data/irs/run.py  #指定程序的启动命令,确保使用的是虚拟环境中的 Python 解释器
Restart=always  #如果程序崩溃,systemd 会自动重启该服务
StandardOutput=syslog   #将输出重定向到系统日志
StandardError=syslog
SyslogIdentifier=irs[Install]
WantedBy=multi-user.target

3.2、服务命令

#重新加载 systemd 配置
sudo systemctl daemon-reload#设置服务开机自启:
sudo systemctl enable irs#服务启动
sudo systemctl start irs#服务重启
sudo systemctl restart irs#服务状态
sudo systemctl status irs

3.3、查看日志

journalctl -u irs.service -f  # 实时查看日志tail -f /var/log/messages