温馨提示×

CentOS下Python代码如何部署

小樊
61
2025-07-21 01:04:50
栏目: 编程语言

在CentOS上部署Python代码可以通过以下步骤完成:

1. 安装Python环境

首先,确保你的CentOS系统已经安装了Python。CentOS 7默认安装的是Python 2.7,但大多数现代Python应用需要Python 3。你可以使用以下命令安装Python 3:

sudo yum install python3

2. 创建虚拟环境

使用虚拟环境可以隔离你的Python应用依赖,避免与其他项目冲突。安装python3-venv包:

sudo yum install python3-venv

然后,创建并激活虚拟环境:

python3 -m venv myenv
source myenv/bin/activate

3. 安装依赖

在你的项目目录中,通常会有一个requirements.txt文件,列出了所有需要的Python包。你可以使用以下命令安装这些依赖:

pip install -r requirements.txt

4. 配置Web服务器

你可以使用多种Web服务器来部署Python应用,比如Gunicorn、uWSGI或Apache。这里以Gunicorn为例。

安装Gunicorn

pip install gunicorn

启动应用

假设你的应用入口文件是app.py,并且有一个名为app的Flask应用实例,你可以使用以下命令启动Gunicorn:

gunicorn -w 4 -b 127.0.0.1:8000 app:app

这会启动4个工作进程,监听在本地8000端口。

5. 配置Nginx作为反向代理

Nginx可以作为反向代理服务器,将请求转发到Gunicorn。

安装Nginx

sudo yum install nginx

配置Nginx

编辑Nginx配置文件,通常位于/etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf,添加以下内容:

server {
    listen 80;
    server_name your_domain.com;
    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;
    }
}

启动Nginx

sudo systemctl start nginx
sudo systemctl enable nginx

6. 配置防火墙

确保你的防火墙允许HTTP(80)和HTTPS(443)流量:

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

7. 使用systemd管理Gunicorn服务

为了使Gunicorn在系统启动时自动运行,可以创建一个systemd服务文件:

sudo nano /etc/systemd/system/gunicorn.service

添加以下内容:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=your_username
Group=nginx
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/your/venv/bin/gunicorn -w 4 -b 127.0.0.1:8000 app:app

[Install]
WantedBy=multi-user.target

然后启动并启用服务:

sudo systemctl start gunicorn
sudo systemctl enable gunicorn

8. 测试部署

打开浏览器,访问你的域名或服务器IP地址,确保应用正常运行。

通过以上步骤,你应该能够在CentOS上成功部署一个Python应用。根据具体需求,你可能还需要进行更多的配置和优化。

0