CentOS 安装 Gunicorn

简介
Gunicorn 是一个 Python WSGI HTTP 服务器,它可以将 WSGI 应用部署到多个进程,以处理并发请求,在 CentOS 系统上安装 Gunicorn 可以让你更高效地运行 Python Web 应用,以下是详细的安装步骤。
系统准备
在开始安装之前,请确保你的 CentOS 系统满足以下要求:
- 操作系统:CentOS 7 或更高版本
- Python 版本:Python 2.7 或 Python 3.x
- 软件包管理器:Yum
安装 Python
由于 Gunicorn 是一个 Python 模块,首先需要确保 Python 已安装在你的系统上,以下是在 CentOS 上安装 Python 的步骤:
使用以下命令更新系统软件包:
sudo yum update
安装 Python:
sudo yum install python3
(可选)如果你需要 Python 2.7,可以使用以下命令安装:
sudo yum install python
安装 Gunicorn
使用以下命令安装 Gunicorn:

sudo yum install python3-gunicorn
(可选)如果你使用的是 Python 2.7,可以使用以下命令安装:
sudo yum install python-gunicorn
验证安装
安装完成后,可以通过以下命令验证 Gunicorn 是否安装成功:
gunicorn --version
如果命令输出类似 gunicorn 20.0.4 的版本信息,则表示 Gunicorn 已成功安装。
配置 Gunicorn
安装 Gunicorn 后,你可以通过以下步骤来配置它:
创建一个虚拟环境(可选):
python3 -m venv myenv source myenv/bin/activate
安装你的 WSGI 应用:
pip install myapp
配置 Gunicorn 以运行你的应用,以下是一个简单的配置示例:

# gunicorn_config.py bind = '0.0.0.0:8000' workers = 4
运行 Gunicorn:
gunicorn -c gunicorn_config.py myapp:app
myapp:app表示你的 WSGI 应用模块和应用程序实例。
常见问题解答(FAQs)
Q1: 如何在非root用户下运行 Gunicorn?
A1: 创建一个非root用户,并为其设置密码,然后使用该用户身份运行 Gunicorn。
sudo useradd myuser sudo passwd myuser su - myuser gunicorn -c gunicorn_config.py myapp:app
Q2: 如何在后台运行 Gunicorn?
A2: 使用 nohup 命令在后台运行 Gunicorn:
nohup gunicorn -c gunicorn_config.py myapp:app &
这样,Gunicorn 将在后台运行,即使终端关闭,它也会继续运行。

