温馨提示×

Ubuntu Python项目如何部署

小樊
36
2025-02-23 20:17:56
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu上部署Python项目可以通过多种方法实现,以下是一些常见的部署步骤:

使用虚拟环境

  1. 安装Python和pip
sudo apt update
sudo apt install python3 python3-pip
  1. 创建虚拟环境
python3 -m venv venv
  1. 激活虚拟环境
source venv/bin/activate
  1. 安装项目依赖
pip install -r requirements.txt
  1. 运行Python脚本
python your_script.py

使用Docker容器

  1. 安装Docker
sudo apt update
sudo apt install docker.io
  1. 创建Dockerfile
# 使用官方的Python基础镜像
FROM python:3.8

# 设置工作目录
WORKDIR /app

# 将当前目录下的所有文件复制到容器的/app目录
COPY . /app

# 安装项目所需的依赖包
RUN pip install --no-cache-dir -r requirements.txt

# 暴露端口,如果有需要的话
EXPOSE 8080

# 运行Python应用
CMD ["python", "your_script.py"]
  1. 构建Docker镜像
docker build -t your_image_name .
  1. 运行Docker容器
docker run -p 8080:8080 your_image_name

使用systemd服务(适用于需要开机自启的项目)

  1. 创建systemd服务文件
[Unit]
Description=My Python Service
After=network.target

[Service]
User=your_username
ExecStart=/home/your_username/miniconda3/envs/my_project_env/bin/python /path/to/your_script.py
Restart=always
RestartSec=10
Environment="PATH=/home/your_username/miniconda3/envs/my_project_env/bin/:$PATH"

[Install]
WantedBy=multi-user.target
  1. 启用并启动服务
sudo systemctl enable my_service.service
sudo systemctl start my_service.service
  1. 检查服务状态
sudo systemctl status my_service.service

以上步骤涵盖了在Ubuntu上部署Python项目的基本流程,包括使用虚拟环境、Docker容器以及systemd服务。根据项目的具体需求,可以选择适合的部署方式。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Python在Ubuntu上如何部署应用

0