在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
目录
背景
Flask 是一个轻量级的 Python Web 框架,广泛应用于开发小型和中型 Web 应用程序。虽然 Flask 自带的开发服务器适用于开发阶段,但在生产环境中,推荐使用 Gunicorn 作为 WSGI 服务器来运行 Flask 应用程序。Gunicorn 是一个高性能的 HTTP 服务器,兼容多种 Web 框架。
在本文中,我们将介绍如何在 Ubuntu 22 系统中使用 Gunicorn 启动一个 Flask 应用程序。
步骤 1: 安装 Flask 和 Gunicorn
首先,需要确保你的系统已经安装了 Flask 和 Gunicorn。你可以使用以下命令安装:
pipenv install flask gunicorn
或者如果你不使用 pipenv,可以直接使用 pip 安装:
pip install flask gunicorn
步骤 2: 创建 Flask 应用程序
在你的项目目录下,创建一个新的 Flask 应用程序。假设我们将文件命名为 app.py,并写入以下代码:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
这段代码创建了一个简单的 Flask 应用,访问根路径时返回 “Hello, World!”。
步骤 3: 使用 Gunicorn 启动 Flask 应用
在开发过程中,Flask 内置的服务器就足够了,但在生产环境中,我们通常使用 Gunicorn 来运行 Flask 应用。使用 Gunicorn 启动 Flask 应用非常简单,执行以下命令:
gunicorn -w 4 app:app
在上述命令中:
-w 4指定 Gunicorn 启动 4 个 worker 进程来处理请求。app:app指定 Flask 应用程序的入口。这里的第一个app是指文件app.py,第二个app是指Flask实例的变量名。
步骤 4: 访问应用程序
如果一切顺利,Gunicorn 会启动 Flask 应用,并在命令行显示类似如下的信息:
[2025-02-22 10:00:00 +0000] [12345] [INFO] Starting gunicorn 20.1.0
[2025-02-22 10:00:00 +0000] [12345] [INFO] Listening at: http://127.0.0.1:8000 (12345)
[2025-02-22 10:00:00 +0000] [12345] [INFO] Using worker: sync
[2025-02-22 10:00:00 +0000] [12346] [INFO] Booting worker with pid: 12346
此时你可以在浏览器中访问 http://127.0.0.1:8000,应该能看到页面上显示 “Hello, World!”。
步骤 5: 配置 Gunicorn 为系统服务(可选)
为了让 Gunicorn 在系统启动时自动运行,可以将其配置为 systemd 服务。首先,创建一个名为 flask_app.service 的 systemd 配置文件:
sudo nano /etc/systemd/system/flask_app.service
在文件中添加以下内容:
[Unit]
Description=Gunicorn instance to serve Flask app
After=network.target
[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu/myflaskapp
ExecStart=/home/ubuntu/.local/bin/gunicorn -w 4 app:app
[Install]
WantedBy=multi-user.target
请根据你的实际情况修改路径、用户名和应用目录。保存并退出编辑器。
然后启用并启动服务:
sudo systemctl start flask_app
sudo systemctl enable flask_app
现在,Gunicorn 将在系统启动时自动启动,并且始终在后台运行。
总结
通过本文的步骤,你已经成功地在 Ubuntu 22 系统上使用 Gunicorn 启动了 Flask 应用程序。在生产环境中,Gunicorn 提供了比 Flask 内置服务器更高的性能和更好的稳定性,因此推荐使用它来运行 Flask 应用程序。如果需要,你还可以将 Gunicorn 配置为 systemd 服务,以便在系统启动时自动运行。
更多推荐

所有评论(0)