在CentOS上部署Python Web应用通常涉及以下几个步骤:
安装Python环境: CentOS系统默认可能没有安装Python,或者只安装了Python 2.x。你需要安装Python 3.x以及pip(Python的包管理工具)。
sudo yum update
sudo yum install python3 python3-pip
安装Web服务器: 你可以使用Apache或Nginx作为Web服务器。这里以Nginx为例。
sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
安装WSGI服务器: WSGI(Web Server Gateway Interface)是Python Web应用和Web服务器之间的接口标准。常用的WSGI服务器有Gunicorn和uWSGI。这里以Gunicorn为例。
pip3 install gunicorn
部署Python Web应用:
假设你的Python Web应用代码在一个名为app.py的文件中,并且你有一个requirements.txt文件列出了所有依赖项。
首先,激活你的虚拟环境(如果你使用了虚拟环境):
source /path/to/your/venv/bin/activate
然后,安装所有依赖项:
pip install -r requirements.txt
接下来,使用Gunicorn启动你的应用。例如,如果你的应用在app.py中定义了一个名为app的应用实例:
gunicorn -w 4 -b 127.0.0.1:8000 app:app
这里的-w 4表示使用4个工作进程,-b 127.0.0.1:8000表示绑定到本地的8000端口。
配置Nginx:
为了让Nginx能够将请求转发到Gunicorn,你需要配置Nginx。编辑Nginx的配置文件(通常位于/etc/nginx/nginx.conf或/etc/nginx/conf.d/default.conf),添加以下内容:
server {
listen 80;
server_name your_domain.com; # 替换为你的域名或公网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;
}
}
然后,重新加载Nginx配置:
sudo systemctl reload nginx
启动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/app
ExecStart=/path/to/your/venv/bin/gunicorn -w 4 -b 127.0.0.1:8000 app:app
[Install]
WantedBy=multi-user.target
替换your_username为你的用户名,/path/to/your/app为你的应用路径。
启用并启动服务:
sudo systemctl enable gunicorn
sudo systemctl start gunicorn
完成以上步骤后,你的Python Web应用应该已经成功部署在CentOS上,并且可以通过浏览器访问了。