本教程适用于以下操作系统版本
- Ubuntu 22.04 (Jammy Jellyfish)
- Ubuntu 20.04 (Focal Fossa)
本页内容
- 先决条件
- 入门
- 安装所需依赖
- 创建虚拟环境
- 设置 Flask 应用
- 配置 uWSGI
- 配置 uWSGI
- 创建 Systemd 服务文件
- 将 Nginx 配置为反向代理
- 使用 Let's Encrypt SSL 保护 Flask 应用
- 结论
Flask 是由 Armin Ronacher 开发的用 Python 编写的微型 Web 框架。它被称为微框架,是因为它不需要任何工具或库。Flask 是一个 Python 模块,拥有一个小型且易于扩展的核心,可帮助你轻松开发 Web 应用。
在本教程中,我们将学习如何在 Ubuntu 20.04 上使用 uWSGI 和 Nginx 部署 Flask 应用。
先决条件
- 一台运行 Ubuntu 20.04 的服务器。
- 一个指向服务器 IP 的有效域名。
- 服务器上已配置 root 密码。
入门
首先,建议将系统软件包更新到最新版本。你可以通过运行以下命令来更新它们:
apt-get update -y
所有软件包更新完成后,你可以继续下一步。
安装所需依赖
接下来,你需要安装部署 Flask 应用所需的一些依赖。你可以使用以下命令安装所有这些依赖:
apt-get install nginx python3-pip python3-dev python3-venv build-essential libssl-dev libffi-dev python3-setuptools -y
所有软件包安装完成后,你可以继续下一步。
创建虚拟环境
接下来,你需要为 Flask 应用创建一个虚拟环境。虚拟环境是一个非常有用的工具,用于创建隔离的 Python 环境。它帮助你为你的项目安装特定版本的 Python。
首先,使用以下命令为 Flask 应用创建一个目录:
mkdir /var/www/html/myapp
接下来,切换目录到 myapp,并使用以下命令创建一个新的 Python 虚拟环境:
cd /var/www/html/myapp
python3.8 -m venv myappenv
接下来,使用以下命令激活虚拟环境:
source myappenv/bin/activate
设置 Flask 应用
此时,Python 虚拟环境已准备好部署 Flask 应用。接下来,你需要在虚拟环境中设置一个 Flask 应用。
首先,使用以下命令安装 Flask 和 uWSGI:
pip install uwsgi flask
接下来,使用以下命令创建一个名为 myapp.py 的示例应用:
nano /var/www/html/myapp/myapp.py
添加以下内容:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "<h1 style='color:blue'>Hi This is My Flask Application</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0')
完成后保存并关闭文件。接下来,使用以下命令运行 Flask 应用:
python /var/www/html/myapp/myapp.py
你应该会看到以下输出:
* Serving Flask app "myapp" (lazy loading) * Environment: production Use a production WSGI server instead. * Debug mode: off * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
现在,打开 Web 浏览器,使用 URL http://your-server-ip:5000 访问你的 Flask 应用。你应该会看到以下界面:

现在,在终端中按 CTRL + C 停止 Flask 应用。
配置 uWSGI
首先,创建一个 WSGI 入口点,告诉 uWSGI 服务器如何与之交互。
nano /var/www/html/myapp/wsgi.py
添加以下内容,从应用中导入 Flask 实例:
from myapp import app
if __name__ == "__main__":
app.run()
完成后保存并关闭文件,然后使用以下命令测试 uWSGI 是否能够为应用提供服务:
uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:app
现在,再次使用 URL http://your-server-ip:5000 访问你的应用。你应该会看到以下界面:
现在,按 CTRL + C 停止应用。
接下来,运行以下命令退出虚拟环境:
deactivate
配置 uWSGI
此时,uWSGI 已能够为你的应用提供服务。现在,使用以下命令创建 uWSGI 配置文件:
nano /var/www/html/myapp/myapp.ini
添加以下内容:
[uwsgi] module = wsgi:app master = true processes = 5 socket = myapp.sock chmod-socket = 660 vacuum = true die-on-term = true
完成后保存并关闭文件。
创建 Systemd 服务文件
接下来,你需要创建一个 systemd 服务文件来管理 uWSGI 服务。你可以使用以下命令创建它:
nano /etc/systemd/system/myapp.service
添加以下内容:
[Unit] Description=uWSGI instance to serve myapp After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/html/myapp Environment="PATH=/var/www/html/myapp/myappenv/bin" ExecStart=/var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini [Install] WantedBy=multi-user.target
完成后保存并关闭文件,然后使用以下命令重新加载 systemd 守护进程:
systemctl daemon-reload
接下来,使用以下命令将应用的所有权更改为 www-data,并设置适当的权限:
chown -R www-data:www-data /var/www/html/myapp
chmod -R 775 /var/www/html/myapp
接下来,使用以下命令启动应用,并使其在系统重启时启动:
systemctl start myapp
systemctl enable myapp
你还可以使用以下命令检查应用的状态:
systemctl status myapp
你应该会得到以下输出:
? myapp.service - uWSGI instance to serve myapp
Loaded: loaded (/etc/systemd/system/myapp.service; disabled; vendor preset: enabled)
Active: active (running) since Sun 2020-09-13 08:38:08 UTC; 1min 53s ago
Main PID: 662796 (uwsgi)
Tasks: 6 (limit: 4691)
Memory: 21.8M
CGroup: /system.slice/myapp.service
??662796 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662808 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662809 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662810 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662811 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
??662812 /var/www/html/myapp/myappenv/bin/uwsgi --ini myapp.ini
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x55e207e7a510 pid: 662796 (default app)
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: *** uWSGI is running in multiple interpreter mode ***
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI master process (pid: 662796)
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 1 (pid: 662808, cores: 1)
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 2 (pid: 662809, cores: 1)
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 3 (pid: 662810, cores: 1)
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 4 (pid: 662811, cores: 1)
Sep 13 08:38:08 ubuntu2004 uwsgi[662796]: spawned uWSGI worker 5 (pid: 662812, cores: 1)
将 Nginx 配置为反向代理
接下来,你需要将 Nginx 配置为反向代理,为 Flask 应用提供服务。你可以使用以下命令完成:
nano /etc/nginx/sites-available/flask.conf
添加以下内容:
server {
listen 80;
server_name flask.example.com;
location / {
include uwsgi_params;
uwsgi_pass unix:/var/www/html/myapp/myapp.sock;
}
}
完成后保存并关闭文件。接下来,使用以下命令检查 Nginx 是否存在语法错误:
nginx -t
你应该会看到以下输出:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
接下来,使用以下命令激活 Nginx 虚拟主机:
ln -s /etc/nginx/sites-available/flask.conf /etc/nginx/sites-enabled/
最后,重启 Nginx 服务以应用更改:
systemctl restart nginx
此时,Nginx 已配置为为你的 Flask 应用提供服务。
使用 Let's Encrypt SSL 保护 Flask 应用
接下来,还建议使用 Let's Encrypt 免费 SSL 保护你的应用。首先,你需要安装 Certbot 客户端来安装和管理 SSL 证书。你可以使用以下命令安装:
apt-get install python3-certbot-nginx -y
安装完成后,运行以下命令,使用 Let's Encrypt SSL 保护你的网站:
certbot --nginx -d flask.example.com
系统将要求你提供有效的电子邮件地址并接受服务条款,如下所示:
Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Enter email address (used for urgent renewal and security notices) (Enter 'c' to cancel): [email protected] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Please read the Terms of Service at https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must agree in order to register with the ACME server at https://acme-v02.api.letsencrypt.org/directory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (A)gree/(C)ancel: A - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Would you be willing to share your email address with the Electronic Frontier Foundation, a founding partner of the Let's Encrypt project and the non-profit organization that develops Certbot? We'd like to send you email about our work encrypting the web, EFF news, campaigns, and ways to support digital freedom. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (Y)es/(N)o: Y Obtaining a new certificate Performing the following challenges: http-01 challenge for flask.example.com Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/flask.conf
接下来,选择是否将 HTTP 流量重定向到 HTTPS,如下所示:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
输入 2 并按 Enter 完成安装。你应该会看到以下输出:
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/flask.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://flask.example.com You should test your configuration at: https://www.ssllabs.com/ssltest/analyze.html?d=flask.example.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/flask.example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/flask.example.com/privkey.pem Your cert will expire on 2020-10-30. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le - We were unable to subscribe you the EFF mailing list because your e-mail address appears to be invalid. You can try again later by visiting https://act.eff.org.
现在,你的 Flask 网站已通过 Let's Encrypt SSL 得到保护。你可以使用 URL https://flask.example.com 访问 Flask 应用。
结论
恭喜!你已成功使用 uWSGI 和 Nginx 部署 Flask 应用,并使用 Let's Encrypt SSL 对其进行了保护。现在你可以轻松地使用 Flask 开发和部署 Python 应用。如有任何问题,欢迎随时向我提问。