在Linux上部署Python应用可以通过多种方式实现,以下是一些常见的方法:
WSGI(Web Server Gateway Interface)是Python Web应用和Web服务器之间的标准接口。
pip install gunicorn
假设你的应用入口文件是app.py,并且有一个名为app的应用实例:
gunicorn -w 4 -b 0.0.0.0:8000 app:app
-w 4 表示使用4个工作进程。-b 0.0.0.0:8000 表示绑定到所有网络接口的8000端口。Nginx可以处理静态文件,并将动态请求转发到Gunicorn或其他WSGI服务器。
sudo apt update
sudo apt install nginx
编辑Nginx配置文件(通常位于/etc/nginx/sites-available/default):
server {
listen 80;
server_name your_domain_or_ip;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static/ {
alias /path/to/your/static/files;
}
}
proxy_pass http://127.0.0.1:8000; 将请求转发到本地的8000端口。location /static/ 处理静态文件。sudo systemctl restart nginx
Docker可以简化部署过程,并确保环境一致性。
在你的项目根目录下创建一个Dockerfile:
# 使用官方Python运行时作为父镜像
FROM python:3.9-slim
# 设置工作目录
WORKDIR /app
# 复制当前目录内容到容器中的/app
COPY . /app
# 安装依赖
RUN pip install --no-cache-dir -r requirements.txt
# 暴露端口
EXPOSE 8000
# 运行应用
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "app:app"]
docker build -t your_app_name .
docker run -d -p 8000:8000 your_app_name
你可以使用systemd来管理你的Python应用,使其在系统启动时自动运行,并在崩溃时自动重启。
在你的项目根目录下创建一个your_app.service文件:
[Unit]
Description=Your Python Application
After=network.target
[Service]
User=your_user
Group=your_group
WorkingDirectory=/path/to/your/project
ExecStart=/usr/local/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable your_app.service
sudo systemctl start your_app.service
通过以上方法,你可以在Linux上部署你的Python应用。选择哪种方法取决于你的具体需求和环境。