如何在Ubuntu 20.04上使用uWSGI和Nginx服务Flask应用程序

A previous version of this tutorial was written by Justin Ellingwood

本教程的先前版本由Justin Ellingwood撰写

介绍 (Introduction)

In this guide, you will build a Python application using the Flask microframework on Ubuntu 20.04. The bulk of this article will be about how to set up the uWSGI application server and how to launch the application and configure Nginx to act as a front-end reverse proxy.

在本指南中,您将在Ubuntu 20.04上使用Flask微框架构建Python应用程序。 本文的大部分内容将涉及如何设置uWSGI应用程序服务器以及如何启动应用程序以及如何配置Nginx充当前端反向代理。

先决条件 (Prerequisites)

Before starting this guide, you should have:

在开始本指南之前,您应该具有:

  • A server with Ubuntu 20.04 installed and a non-root user with sudo privileges. Follow our initial server setup guide for guidance.

    安装了Ubuntu 20.04的服务器以及具有sudo特权的非root用户。 请遵循我们的初始服务器设置指南以获取指导。

  • Nginx installed, following Steps 1 through 3 of How To Install Nginx on Ubuntu 20.04.

    按照如何在Ubuntu 20.04上安装Nginx的 步骤1至3进行安装

  • A domain name configured to point to your server. You can purchase one on Namecheap or get one for free on Freenom. You can learn how to point domains to DigitalOcean by following the relevant documentation on domains and DNS. This tutorial assumes you’ve created the following DNS records:

    配置为指向您的服务器的域名。 你可以购买一个Namecheap或免费获得一个上Freenom 。 您可以通过遵循有关域和DNS的相关文档,学习如何将域指向DigitalOcean。 本教程假定您已创建以下DNS记录:

    • An A record with your_domain pointing to your server’s public IP address.

      A记录,其中your_domain指向服务器的公共IP地址。

    • An A record with www.your_domain pointing to your server’s public IP address.

      www. your_domain的A记录www. your_domain www. your_domain指向服务器的公共IP地址。

Additionally, it may be helpful to have some familiarity with uWSGI, the application server you’ll set up in this guide, and the WSGI specification. This discussion of definitions and concepts goes over both in detail.

此外,熟悉uWSGI,您将在本指南中设置的应用程序服务器以及WSGI规范可能会有所帮助。 对定义和概念的讨论在这两者上都进行了详细介绍。

第1步—从Ubuntu存储库安装组件 (Step 1 — Installing the Components from the Ubuntu Repositories)

Your first step will be to install all of the pieces that you need from the Ubuntu repositories. The packages you need to install include pip, the Python package manager, to manage your Python components. You’ll also get the Python development files necessary to build uWSGI.

第一步是从Ubuntu存储库安装所需的所有组件。 您需要安装的软件包包括Python软件包管理器pip ,以管理您的Python组件。 您还将获得构建uWSGI所需的Python开发文件。

First, update the local package index:

首先,更新本地包索引:

  • sudo apt update

    sudo apt更新

Then install the packages that will allow you to build your Python environment. These will include python3-pip, along with a few more packages and development tools necessary for a robust programming environment:

然后安装将允许您构建Python环境的软件包。 这些将包括python3-pip ,以及健壮的编程环境所需的其他一些软件包和开发工具:

  • sudo apt install python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools

    须藤apt install python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools

With these packages in place, you’re ready to move on to creating a virtual environment for your project.

有了这些软件包之后,您就可以继续为项目创建虚拟环境了。

第2步-创建Python虚拟环境 (Step 2 — Creating a Python Virtual Environment)

A Python virtual environment is a self-contained project directory that contains specific versions of Python and the Python modules required for the given project. This is useful for isolating one application from others on the same system by managing each one’s dependencies separately. In this step, you’ll set up a Python virtual environment from which you’ll run your Flask application.

Python虚拟环境是一个独立的项目目录,其中包含特定版本的Python和给定项目所需的Python模块。 通过分别管理每个应用程序的依赖关系,这对于将一个应用程序与同一系统上的其他应用程序隔离非常有用。 在此步骤中,您将设置一个Python虚拟环境,从该虚拟环境将运行Flask应用程序。

Start by installing the python3-venv package, which will install the venv module:

首先安装python3-venv软件包,该软件包将安装venv模块:

  • sudo apt install python3-venv

    sudo apt安装python3-venv

Next, make a parent directory for your Flask project:

接下来,为Flask项目创建一个父目录:

  • mkdir ~/myproject

    mkdir〜/ myproject

Move into the directory after you create it:

创建目录后,移至该目录:

  • cd ~/myproject

    cd〜/ myproject

Create a virtual environment to store your Flask project’s Python requirements by typing:

通过键入以下内容,创建一个虚拟环境来存储Flask项目的Python要求:

  • python3.8 -m venv myprojectenv

    python3.8 -m venv myprojectenv

This will install a local copy of Python and pip into a directory called myprojectenv within your project directory.

这会将Python的本地副本和pip安装到项目目录中名为myprojectenv的目录中。

Before installing applications within the virtual environment, you need to activate it. Do so by typing:

在虚拟环境中安装应用程序之前,需要激活它。 通过键入以下内容:

  • source myprojectenv/bin/activate

    源myprojectenv / bin / activate

Your prompt will change to indicate that you are now operating within the virtual environment. It will look something like this: (myprojectenv)user@host:~/myproject$.

您的提示将更改以指示您现在正在虚拟环境中操作。 它看起来像这样: ( myprojectenv ) user @ host :~/ myproject $

步骤3 —设置Flask应用程序 (Step 3 — Setting Up a Flask Application)

Now that you are in your virtual environment, you can install Flask and uWSGI and then get started on designing your application.

现在您已经处于虚拟环境中,可以安装Flask和uWSGI,然后开始设计应用程序。

First, install wheel with the local instance of pip to ensure that your packages will install even if they are missing wheel archives:

首先,使用本地pip实例安装wheel以确保您的软件包即使丢失wheel档案也能安装:

  • pip install wheel

    点安装轮

Note: Regardless of which version of Python you are using, when the virtual environment is activated, you should use the pip command (not pip3).

注意 :无论使用哪种版本的Python,在激活虚拟环境时,都应使用pip命令(而非pip3 )。

Next, install Flask and uWSGI:

接下来,安装Flask和uWSGI:

  • pip install uwsgi flask

    pip安装uwsgi烧瓶

创建示例应用 (Creating a Sample App)

Now that you have Flask available, you can create a sample application. Flask is a microframework. It does not include many of the tools that more full-featured frameworks might, and exists mainly as a module that you can import into your projects to assist you in initializing a web application.

现在您可以使用Flask了,您可以创建一个示例应用程序。 烧瓶是一个微框架。 它不包含功能更全的框架可能提供的许多工具,并且主要作为模块存在,您可以将其导入项目中以帮助您初始化Web应用程序。

While your application might be more complex, in this example you’ll create your Flask app in a single file, called myproject.py:

尽管您的应用程序可能更复杂,但在本示例中,您将在一个名为myproject.py文件中创建Flask应用程序:

  • nano ~/myproject/myproject.py

    纳米〜/ myproject / myproject .py

The application code will live in this file. It will import Flask and instantiate a Flask object. You can use this to define the functions that you want to be run when a specific route is requested:

应用程序代码将存在于此文件中。 它将导入Flask并实例化一个Flask对象。 您可以使用它来定义要在请求特定路由时运行的功能:

~/myproject/myproject.py
〜/ myproject / myproject.py
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "<h1 style='color:blue'>Hello There!</h1>"

if __name__ == "__main__":
    app.run(host='0.0.0.0')

Essentially, this defines what content to present to whoever accesses the root domain. Save and close the file when you’re finished. If you used nano to edit the file, as in the previous example, do so by pressing CTRL + X, Y, and then ENTER.

本质上,这定义了向根域访问者呈现的内容。 完成后保存并关闭文件。 如果像上一个示例那样使用nano来编辑文件,请按CTRL + XY ,然后按ENTER

If you followed the initial server setup guide, you should have a UFW firewall enabled. To test the application, you need to allow access to port 5000:

如果遵循初始服务器安装指南,则应启用UFW防火墙。 要测试该应用程序,您需要允许访问端口5000

  • sudo ufw allow 5000

    须藤ufw允许5000

Now, you can test your Flask app by typing:

现在,您可以通过键入以下内容来测试Flask应用程序:

  • python myproject.py

    python myproject .py

You will see output like the following, including a helpful warning reminding you not to use this server setup in production:

您将看到类似以下的输出,包括一个有用的警告,提醒您不要在生产中使用此服务器设置:


   
   
Output
* Serving Flask app "myproject" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

Visit your server’s IP address followed by :5000 in your web browser:

在网络浏览器中访问服务器的IP地址,然后输入:5000

http://your_server_ip:5000

You will see something like this:

您将看到如下内容:

When you are finished, hit CTRL + C in your terminal window to stop the Flask development server.

完成后,在终端窗口中按CTRL + C以停止Flask开发服务器。

创建WSGI入口点 (Creating the WSGI Entry Point)

Next, create a file that will serve as the entry point for your application. This will tell your uWSGI server how to interact with it.

接下来,创建一个文件,将其用作应用程序的入口点。 这将告诉您的uWSGI服务器如何与之交互。

Call the file wsgi.py:

调用文件wsgi.py

  • nano ~/myproject/wsgi.py

    纳米〜/ myproject /wsgi.py

In this file, import the Flask instance from your application and then run it:

在此文件中,从您的应用程序导入Flask实例,然后运行它:

~/myproject/wsgi.py
〜/ myproject / wsgi.py
from myproject import app

if __name__ == "__main__":
    app.run()

Save and close the file when you are finished.

完成后保存并关闭文件。

第4步-配置uWSGI (Step 4 — Configuring uWSGI)

Your application is now written with an entry point established. You can move on to configuring uWSGI.

现在,您的应用程序已建立一个入口点。 您可以继续配置uWSGI。

测试uWSGI是否可以服务应用程序 (Testing Whether uWSGI Can Serve the Application)

As a first step, test to make sure that uWSGI can correctly serve your application by passing it the name of your entry point. This is constructed by the name of the module (minus the .py extension) plus the name of the callable within the application. In the context of this tutorial, the name of the entry point is wsgi:app.

作为第一步,请进行测试以确保uWSGI通过为其输入入口点名称来正确地为您的应用程序提供服务。 这是由模块的名称(减去.py扩展名)加上应用程序中可调用的名称构成的。 在本教程的上下文中,入口点的名称为wsgi:app

Also, specify the socket so that it will be started on a publicly available interface, as well as the protocol, so that it will use HTTP instead of the uwsgi binary protocol. Use the same port number, 5000, that you opened earlier:

另外,请指定套接字,以便它将在公共可用接口以及协议上启动,以便它将使用HTTP而不是uwsgi二进制协议。 使用先前打开的端口号5000

  • uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:app

    uwsgi --socket 0.0.0.0:5000 --protocol = http -w wsgi:app

Visit your server’s IP address with :5000 appended to the end in your web browser again:

在您的Web浏览器中再次访问服务器IP地址(末尾附加:5000

http://your_server_ip:5000

You will see your application’s output again:

您将再次看到应用程序的输出:

When you have confirmed that it’s functioning properly, press CTRL + C in your terminal window.

确认其功能正常后,请在终端窗口中按CTRL + C

You’re now done with your virtual environment, so you can deactivate it:

现在您已经完成了虚拟环境,因此可以将其停用:

  • deactivate

    停用

Any Python commands will now use the system’s Python environment again.

现在,所有Python命令都将再次使用系统的Python环境。

创建一个uWSGI配置文件 (Creating a uWSGI Configuration File)

You have tested that uWSGI is able to serve your application, but ultimately you will want something more robust for long-term usage. You can create a uWSGI configuration file with the relevant options for this.

您已经测试过uWSGI能够为您的应用程序提供服务,但是最终您将需要更强大的功能来长期使用。 您可以创建带有相关选项的uWSGI配置文件。

Place that file in your project directory and call it myproject.ini:

将该文件放在您的项目目录中,并将其命名为myproject.ini

  • nano ~/myproject/myproject.ini

    纳米〜/ myproject / myproject .ini

Inside, start the file off with the [uwsgi] header so that uWSGI knows to apply the settings. Below that, specify module itself — by referring to the wsgi.py file minus the extension — and the callable within the file, app:

在内部,使用[uwsgi]标头启动文件,以便uWSGI知道应用设置。 在此之下,指定模块本身-通过引用wsgi.py文件减去扩展名-以及文件app的可调用项:

~/myproject/myproject.ini
〜/ myproject / myproject.ini
[uwsgi]
module = wsgi:app

Next, tell uWSGI to start up in master mode and spawn five worker processes to serve actual requests:

接下来,告诉uWSGI以主模式启动,并生成五个工作进程来满足实际请求:

~/myproject/myproject.ini
〜/ myproject / myproject.ini
[uwsgi]
module = wsgi:app

master = true
processes = 5

When you were testing, you exposed uWSGI on a network port. However, you’re going to be using Nginx to handle actual client connections, which will then pass requests to uWSGI. Since these components are operating on the same computer, a Unix socket is preferable because it is faster and more secure. Call the socket myproject.sock and place it in this directory.

在测试时,您在网络端口上公开了uWSGI。 但是,您将使用Nginx处理实际的客户端连接,然后将请求传递给uWSGI。 由于这些组件在同一台计算机上运行,​​因此最好使用Unix套接字,因为它更快,更安全。 调用套接字myproject .sock并将其放置在此目录中。

Next, change the permissions on the socket. You’ll be giving the Nginx group ownership of the uWSGI process later on, so you need to make sure the group owner of the socket can read information from it and write to it. Also, add the vacuum option and set it to true; this will clean up the socket when the process stops:

接下来,更改套接字上的权限。 稍后,您将授予uWSGI进程的Nginx组所有权,因此您需要确保套接字的组所有者可以从中读取信息并将其写入。 另外,添加vacuum选项并将其设置为true; 这将在进程停止时清理套接字:

~/myproject/myproject.ini
〜/ myproject / myproject.ini
[uwsgi]
module = wsgi:app

master = true
processes = 5

socket = myproject.sock
chmod-socket = 660
vacuum = true

The last thing to do is set the die-on-term option. This can help ensure that the init system and uWSGI have the same assumptions about what each process signal means. Setting this aligns the two system components, implementing the expected behavior:

最后要做的是设置die-on-term选项。 这可以帮助确保init系统和uWSGI对每个过程信号的含义具有相同的假设。 设置它使两个系统组件对齐,实现预期的行为:

~/myproject/myproject.ini
〜/ myproject / myproject.ini
[uwsgi]
module = wsgi:app

master = true
processes = 5

socket = myproject.sock
chmod-socket = 660
vacuum = true

die-on-term = true

You may have noticed that these lines do not specify a protocol like you did from the command line. That is because by default, uWSGI speaks using the uwsgi protocol, a fast binary protocol designed to communicate with other servers. Nginx can speak this protocol natively, so it’s better to use this than to force communication by HTTP.

您可能已经注意到,这些行没有像在命令行中那样指定协议。 这是因为在默认情况下,uWSGI讲使用uwsgi协议,快速二进制协议设计与其他服务器进行通信。 Nginx可以原生地使用此协议,因此使用此协议比通过HTTP强制通信更好。

When you are finished, save and close the file.

完成后,保存并关闭文件。

With that, uWSGI is configured on your system. In order to give you more flexibility in how you manage your Flask application, you can now configure it to run as a systemd service.

这样,即可在系统上配置uWSGI。 为了在管理Flask应用程序方面提供更大的灵活性,您现在可以将其配置为作为systemd服务运行。

步骤5 —创建一个systemd单位文件 (Step 5 — Creating a systemd Unit File)

Systemd is a suite of tools that provides a fast and flexible init model for managing system services. Creating a systemd unit file will allow Ubuntu’s init system to automatically start uWSGI and serve the Flask application whenever the server boots.

Systemd是一套工具,可提供快速灵活的初始化模型来管理系统服务。 创建一个systemd单位文件将使Ubuntu的init系统可以在服务器启动时自动启动uWSGI并为Flask应用程序提供服务。

Create a unit file ending in .service within the /etc/systemd/system directory to begin:

/etc/systemd/system目录中创建一个以.service结尾的单元文件以开始:

  • sudo nano /etc/systemd/system/myproject.service

    须藤nano / etc / systemd / system / myproject .service

Inside, start with the [Unit] section, which is used to specify metadata and dependencies. Then put a description of the service here and tell the init system to only start this after the networking target has been reached:

在内部,从[Unit]部分开始,该部分用于指定元数据和依赖项。 然后在此处对服务进行描述,并告诉init系统仅在达到网络目标后才启动该服务:

/etc/systemd/system/myproject.service
/etc/systemd/system/myproject.service
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

Next, open up the [Service] section. This will specify the user and group that you want the process to run under. Give your regular user account ownership of the process since it owns all of the relevant files. Then give group ownership to the www-data group so that Nginx can communicate easily with the uWSGI processes. Remember to replace the username here with your username:

接下来,打开[Service]部分。 这将指定要在其中运行进程的用户和组。 由于该过程拥有所有相关文件,因此请授予您的常规用户帐户对该过程的所有权。 然后将组所有权授予www-data组,以便Nginx可以轻松地与uWSGI进程进行通信。 请记住,将此处的用户名替换为您的用户名:

/etc/systemd/system/myproject.service
/etc/systemd/system/myproject.service
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=sammy
Group=www-data

Next, map out the working directory and set the PATH environmental variable so that the init system knows that the executables for the process are located within your virtual environment. Also, specify the command to start the service. Systemd requires that you give the full path to the uWSGI executable, which is installed within your virtual environment. Here, we pass the name of the .ini configuration file you created in your project directory.

接下来,映射工作目录并设置PATH环境变量,以便init系统知道该进程的可执行文件位于您的虚拟环境中。 另外,指定命令以启动服务。 Systemd要求您提供uWSGI可执行文件的完整路径,该文件已安装在虚拟环境中。 在这里,我们传递您在项目目录中创建的.ini配置文件的名称。

Remember to replace the username and project paths with your own information:

请记住用您自己的信息替换用户名和项目路径:

/etc/systemd/system/myproject.service
/etc/systemd/system/myproject.service
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myproject
Environment="PATH=/home/sammy/myproject/myprojectenv/bin"
ExecStart=/home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini

Finally, add an [Install] section. This will tell systemd what to link this service to if you enable it to start at boot. In this case, set the service to start when the regular multi-user system is up and running:

最后,添加一个[Install]部分。 如果您启用该服务以在启动时启动,它将告诉systemd该服务链接到什么。 在这种情况下,将服务设置为在常规多用户系统启动并运行时启动:

/etc/systemd/system/myproject.service
/etc/systemd/system/myproject.service
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myproject
Environment="PATH=/home/sammy/myproject/myprojectenv/bin"
ExecStart=/home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini

[Install]
WantedBy=multi-user.target

With that, your systemd service file is complete. Save and close it now.

这样,您的systemd服务文件就完成了。 立即保存并关闭。

You can now start the uWSGI service you created:

现在,您可以启动创建的uWSGI服务:

  • sudo systemctl start myproject

    sudo systemctl启动myproject

Then enable it so that it starts at boot:

然后启用它,使其在启动时启动:

  • sudo systemctl enable myproject

    sudo systemctl启用myproject

Check the status:

检查状态:

  • sudo systemctl status myproject

    sudo systemctl状态为myproject

You will see output like this:

您将看到如下输出:


   
   
Output
● myproject.service - uWSGI instance to serve myproject Loaded: loaded (/etc/systemd/system/myproject.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2020-05-20 13:21:39 UTC; 8h ago Main PID: 22146 (uwsgi) Tasks: 6 (limit: 2345) Memory: 25.5M CGroup: /system.slice/myproject.service ├─22146 /home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini ├─22161 /home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini ├─22162 /home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini ├─22163 /home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini ├─22164 /home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini └─22165 /home/sammy/myproject/myprojectenv/bin/uwsgi --ini myproject.ini

If you see any errors, be sure to resolve them before continuing with the tutorial. Otherwise, you can move on to configuring your Nginx installation to pass requests to the myproject.sock socket.

如果看到任何错误,请确保在继续本教程之前解决它们。 否则,您可以继续配置Nginx安装,以将请求传递到myproject .sock套接字。

第6步—配置Nginx代理请求 (Step 6 — Configuring Nginx to Proxy Requests)

Your uWSGI application server is now up and running, waiting for requests on the socket file in the project directory. In this step, you’ll configure Nginx to pass web requests to that socket using the uwsgi protocol.

您的uWSGI应用程序服务器现在已启动并正在运行,正在等待项目目录中套接字文件上的请求。 在此步骤中,您将配置Nginx使用uwsgi协议将Web请求传递到该套接字。

Begin by creating a new server block configuration file in Nginx’s sites-available directory. To keep in line with the rest of the guide, the following example refers to this as myproject:

首先在Nginx的sites-available目录中创建一个新的服务器块配置文件。 为了与指南的其余部分保持一致,以下示例将其称为myproject

  • sudo nano /etc/nginx/sites-available/myproject

    须藤纳米/ etc / nginx / sites-available / myproject

Open up a server block and tell Nginx to listen on the default port 80. Additionally, tell it to use this block for requests for your server’s domain name:

打开一个服务器块,告诉Nginx在默认端口80上侦听。 另外,告诉它使用此块来请求服务器域名:

/etc/nginx/sites-available/myproject
/ etc / nginx / sites-available / myproject
server {
    listen 80;
    server_name your_domain www.your_domain;
}

Next, add a location block that matches every request. Within this block, include the uwsgi_params file that specifies some general uWSGI parameters that need to be set. Then pass the requests to the socket you defined using the uwsgi_pass directive:

接下来,添加一个匹配每个请求的位置块。 在此块中,包括uwsgi_params文件,该文件指定一些需要设置的常规uWSGI参数。 然后使用uwsgi_pass指令将请求传递到您定义的套接字:

/etc/nginx/sites-available/myproject
/ etc / nginx / sites-available / myproject
server {
    listen 80;
    server_name your_domain www.your_domain;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/sammy/myproject/myproject.sock;
    }
}

Save and close the file when you’re finished.

完成后保存并关闭文件。

To enable the Nginx server block configuration you’ve just created, link the file to the sites-enabled directory:

要启用刚刚创建的Nginx服务器块配置,请将文件链接到sites-enabled目录:

  • sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

    须藤ln -s / etc / nginx / sites-available / myproject / etc / nginx / sites-enabled

With the file in that directory, you can test for syntax errors by typing:

使用该目录中的文件,您可以通过键入以下内容来测试语法错误:

  • sudo nginx -t

    须藤Nginx -t

If this returns without indicating any issues, restart the Nginx process to read the new configuration:

如果返回结果没有指示任何问题,请重新启动Nginx进程以读取新配置:

  • sudo systemctl restart nginx

    sudo systemctl重启nginx

Finally, adjust the firewall once again. You no longer need access through port 5000, so you can remove that rule. Then, you can allow access to the Nginx server:

最后,再次调整防火墙。 您不再需要通过端口5000访问,因此可以删除该规则。 然后,您可以允许访问Nginx服务器:

  • sudo ufw delete allow 5000

    sudo ufw删除允许5000
  • sudo ufw allow 'Nginx Full'

    sudo ufw允许'Nginx Full'

You will now be able to navigate to your server’s domain name in your web browser:

现在,您将能够在Web浏览器中导航到服务器的域名:

http://your_domain

You will see your application output:

您将看到您的应用程序输出:

If you encounter any errors, trying checking the following:

如果遇到任何错误,请尝试检查以下内容:

  • sudo less /var/log/nginx/error.log: checks the Nginx error logs.

    sudo less /var/log/nginx/error.log :检查Nginx错误日志。

  • sudo less /var/log/nginx/access.log: checks the Nginx access logs.

    sudo less /var/log/nginx/access.log :检查Nginx访问日志。

  • sudo journalctl -u nginx: checks the Nginx process logs.

    sudo journalctl -u nginx :检查Nginx进程日志。

  • sudo journalctl -u myproject: checks your Flask app’s uWSGI logs.

    sudo journalctl -u myproject :检查Flask应用程序的uWSGI日志。

步骤7 —保护应用程序的安全 (Step 7 — Securing the Application)

To ensure that traffic to your server remains secure, obtain an SSL certificate for your domain. There are multiple ways to do this, including getting a free certificate from Let’s Encrypt, generating a self-signed certificate, or buying one from a commercial provider. For the sake of expediency, this tutorial explains how to obtain a free certificate from Let’s Encrypt.

为确保流向服务器的流量保持安全,请获取您域的SSL证书。 有多种方法可以做到这一点,包括从Let's Encrypt获得免费证书,生成自签名证书或从商业提供商那里购买证书。 为了方便起见,本教程说明了如何从Let's Encrypt获得免费证书。

First, install Certbot and its Nginx plugin with apt:

首先,使用apt安装Certbot及其Nginx插件:

  • sudo apt install certbot python3-certbot-nginx

    sudo apt安装certbot python3-certbot-nginx

Certbot provides a variety of ways to obtain SSL certificates through plugins. The Nginx plugin will take care of reconfiguring Nginx and reloading the config whenever necessary. To use this plugin, type the following:

Certbot提供了多种通过插件获取SSL证书的方法。 Nginx插件将负责重新配置Nginx并在必要时重新加载配置。 要使用此插件,请键入以下内容:

  • sudo certbot --nginx -d your_domain -d www.your_domain

    sudo certbot --nginx -d your_domain -d www。 your_domain

This runs certbot with the --nginx plugin, using -d to specify the names you’d like the certificate to be valid for.

这将使用--nginx插件运行certbot ,并使用-d指定您希望证书有效的名称。

If this is your first time running certbot on this server, you will be prompted to enter an email address and agree to the terms of service. After doing so, certbot will communicate with the Let’s Encrypt server, then run a challenge to verify that you control the domain you’re requesting a certificate for.

如果这是您第一次在该服务器上运行certbot ,则系统将提示您输入电子邮件地址并同意服务条款。 完成此操作后, certbot将与Let's Encrypt服务器通信,然后进行质询以验证您是否控制了要为其申请证书的域。

If that’s successful, certbot will ask how you’d like to configure your HTTPS settings:

如果成功, certbot将询问您如何配置HTTPS设置:


   
   
Output
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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):

Select your choice then hit ENTER. The configuration will be updated, and Nginx will reload to pick up the new settings. certbot will wrap up with a message telling you the process was successful and where your certificates are stored:

选择您的选择,然后按ENTER 。 配置将被更新,并且Nginx将重新加载以获取新设置。 certbot将以一条消息结束,告诉您该过程已成功完成,并且证书的存储位置:


   
   
Output
IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/your_domain/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/your_domain/privkey.pem Your cert will expire on 2020-08-18. 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

If you followed the Nginx installation instructions in the prerequisites, you will no longer need the redundant HTTP profile allowance:

如果按照先决条件中的Nginx安装说明进行操作,则将不再需要冗余HTTP配置文件配额:

  • sudo ufw delete allow 'Nginx HTTP'

    sudo ufw delete allow'Nginx HTTP'

To verify the configuration, navigate once again to your domain, using https://:

要验证配置,请使用https://再次导航到您的域:

https://your_domain

You will see your application output once again, along with your browser’s security indicator, which should indicate that the site is secured.

您将再次看到应用程序输出以及浏览器的安全指示符,该安全指示符应指示该站点已被保护。

结论 (Conclusion)

In this guide, you created and secured a basic Flask application within a Python virtual environment. Then you created a WSGI entry point so that any WSGI-capable application server can interface with it, and then configured the uWSGI app server to provide this function. Afterwards, you created a systemd service file to automatically launch the application server on boot. You also created an Nginx server block that passes web client traffic to the application server, thereby relaying external requests, and secured traffic to your server with Let’s Encrypt.

在本指南中,您在Python虚拟环境中创建并保护了基本的Flask应用程序。 然后,您创建了一个WSGI入口点,以便任何支持WSGI的应用程序服务器都可以与之交互,然后配置uWSGI应用程序服务器以提供此功能。 之后,您创建了systemd服务文件以在启动时自动启动应用程序服务器。 您还创建了一个Nginx服务器块,该块将Web客户端流量传递到应用程序服务器,从而中继外部请求,并使用Let's Encrypt保护到服务器的流量安全。

Flask is a simple yet flexible framework meant to provide your applications with functionality without being too restrictive about structure or design. You can use the general stack described in this guide to serve the flask applications that you design.

Flask是一个简单而灵活的框架,旨在为您的应用程序提供功能,而不必过于限制结构或设计。 您可以使用本指南中描述的常规堆栈来服务您设计的烧瓶应用程序。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-20-04

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值