介绍 (Introduction)
Django is a powerful web framework that can help you get your Python application or website off the ground. Django includes a simplified development server for testing your code locally, but for anything even slightly production related, a more secure and powerful web server is required.
Django是一个功能强大的网络框架,可以帮助您启动Python应用程序或网站。 Django包括一个简化的开发服务器,用于在本地测试您的代码,但是对于任何与生产无关的事情,都需要一个更安全,更强大的Web服务器。
In this guide, we will demonstrate how to install and configure some components on Ubuntu 20.04 to support and serve Django applications. We will be setting up a PostgreSQL database instead of using the default SQLite database. We will configure the Gunicorn application server to interface with our applications. We will then set up Nginx to reverse proxy to Gunicorn, giving us access to its security and performance features to serve our apps.
在本指南中,我们将演示如何在Ubuntu 20.04上安装和配置一些组件以支持和服务Django应用程序。 我们将建立一个PostgreSQL数据库,而不是使用默认SQLite数据库。 我们将配置Gunicorn应用程序服务器以与我们的应用程序接口。 然后,我们将设置Nginx来反向代理Gunicorn,从而使我们能够使用其安全性和性能功能来服务我们的应用程序。
先决条件和目标 (Prerequisites and Goals)
In order to complete this guide, you should have a fresh Ubuntu 20.04 server instance with a basic firewall and a non-root user with sudo
privileges configured. You can learn how to set this up by running through our initial server setup guide.
为了完成本指南,您应该具有一个全新的Ubuntu 20.04服务器实例,该实例具有基本防火墙和配置了sudo
特权的非root用户。 您可以通过运行我们的初始服务器设置指南来了解如何进行设置。
We will be installing Django within a virtual environment. Installing Django into an environment specific to your project will allow your projects and their requirements to be handled separately.
我们将在虚拟环境中安装Django。 将Django安装到特定于您的项目的环境中将使您的项目及其要求可以分别处理。
Once we have our database and application up and running, we will install and configure the Gunicorn application server. This will serve as an interface to our application, translating client requests from HTTP to Python calls that our application can process. We will then set up Nginx in front of Gunicorn to take advantage of its high performance connection handling mechanisms and its easy-to-implement security features.
一旦数据库和应用程序启动并运行,我们将安装和配置Gunicorn应用程序服务器。 这将用作我们应用程序的接口,将客户端请求从HTTP转换为我们的应用程序可以处理的Python调用。 然后,我们将在Gunicorn前面设置Nginx,以利用其高性能的连接处理机制和易于实现的安全功能。
Let’s get started.
让我们开始吧。
从Ubuntu存储库安装软件包 (Installing the Packages from the Ubuntu Repositories)
To begin the process, we’ll download and install all of the items we need from the Ubuntu repositories. We will use the Python package manager pip
to install additional components a bit later.
要开始此过程,我们将从Ubuntu存储库中下载并安装所需的所有项目。 稍后,我们将使用Python包管理器pip
安装其他组件。
We need to update the local apt
package index and then download and install the packages. The packages we install depend on which version of Python your project will use.
我们需要更新本地apt
软件包索引,然后下载并安装软件包。 我们安装的软件包取决于您的项目将使用哪个Python版本。
If you are using Django with Python 3, type:
如果您将Django与Python 3配合使用,请输入:
- sudo apt update sudo apt更新
- sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl sudo apt安装python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl
Django 1.11 is the last release of Django that will support Python 2. If you are starting new projects, it is strongly recommended that you choose Python 3. If you still need to use Python 2, type:
Django 1.11是支持Python 2的Django最新版本。如果要启动新项目,强烈建议您选择Python3。如果仍然需要使用Python 2 ,请输入:
- sudo apt update sudo apt更新
- sudo apt install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx curl sudo apt安装python-pip python-dev libpq-dev postgresql postgresql-contrib nginx curl
This will install pip
, the Python development files needed to build Gunicorn later, the Postgres database system and the libraries needed to interact with it, and the Nginx web server.
这将安装pip
,以后构建Gunicorn所需的Python开发文件,Postgres数据库系统以及与其进行交互所需的库以及Nginx Web服务器。
创建PostgreSQL数据库和用户 (Creating the PostgreSQL Database and User)
We’re going to jump right in and create a database and database user for our Django application.
我们将直接进入并为Django应用程序创建数据库和数据库用户。
By default, Postgres uses an authentication scheme called “peer authentication” for local connections. Basically, this means that if the user’s operating system username matches a valid Postgres username, that user can login with no further authentication.
默认情况下,Postgres对本地连接使用一种称为“对等身份验证”的身份验证方案。 基本上,这意味着如果用户的操作系统用户名与有效的Postgres用户名匹配,则该用户无需进一步的身份验证即可登录。
During the Postgres installation, an operating system user named postgres
was created to correspond to the postgres
PostgreSQL administrative user. We need to use this user to perform administrative tasks. We can use sudo and pass in the username with the -u
option.
在安装Postgres的过程中,创建了一个名为postgres
的操作系统用户,以对应于postgres
PostgreSQL管理用户。 我们需要使用该用户来执行管理任务。 我们可以使用sudo并使用-u
选项传递用户名。
Log into an interactive Postgres session by typing:
通过键入以下内容来登录交互式Postgres会话:
- sudo -u postgres psql 须藤-u postgres psql
You will be given a PostgreSQL prompt where we can set up our requirements.
您将获得一个PostgreSQL提示,我们可以在其中设置我们的要求。
First, create a database for your project:
首先,为您的项目创建一个数据库:
CREATE DATABASE myproject;
创建数据库myproject ;
Note: Every Postgres statement must end with a semi-colon, so make sure that your command ends with one if you are experiencing issues.
注意:每个Postgres语句都必须以分号结尾,因此如果遇到问题,请确保命令以1结尾。
Next, create a database user for our project. Make sure to select a secure password:
接下来,为我们的项目创建一个数据库用户。 确保选择一个安全密码:
CREATE USER myprojectuser WITH PASSWORD 'password';
使用密码“ password ”创建用户myprojectuser ;
Afterwards, we’ll modify a few of the connection parameters for the user we just created. This will speed up database operations so that the correct values do not have to be queried and set each time a connection is established.
然后,我们将为刚刚创建的用户修改一些连接参数。 这将加速数据库操作,从而不必在每次建立连接时都查询和设置正确的值。
We are setting the default encoding to UTF-8
, which Django expects. We are also setting the default transaction isolation scheme to “read committed”, which blocks reads from uncommitted transactions. Lastly, we are setting the timezone. By default, our Django projects will be set to use UTC
. These are all recommendations from the Django project itself:
我们将Django期望的默认编码设置为UTF-8
。 我们还将默认事务隔离方案设置为“读已提交”,该方案将阻止未提交事务的读取。 最后,我们设置时区。 默认情况下,我们的Django项目将设置为使用UTC
。 这些都是Django项目本身的建议:
ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
ALTER ROLE myprojectuser将 client_encoding设置为'utf8';
ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myprojectuser设置default_transaction_isolation为'read commit';
ALTER ROLE myprojectuser SET timezone TO 'UTC';
ALTER ROLE myprojectuser将时区设置为“ UTC”;
Now, we can give our new user access to administer our new database:
现在,我们可以授予新用户访问权限来管理新数据库:
GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
将数据库myproject上的所有特权授予 myprojectuser ;
When you are finished, exit out of the PostgreSQL prompt by typing:
完成后,通过键入以下命令退出PostgreSQL提示符:
- \q \ q
Postgres is now set up so that Django can connect to and manage its database information.
现在已经设置了Postgres,以便Django可以连接到并管理其数据库信息。
为您的项目创建Python虚拟环境 (Creating a Python Virtual Environment for your Project)
Now that we have our database, we can begin getting the rest of our project requirements ready. We will be installing our Python requirements within a virtual environment for easier management.
现在我们有了数据库,我们可以开始准备其余的项目需求。 我们将在虚拟环境中安装Python要求,以简化管理。
To do this, we first need access to the virtualenv
command. We can install this with pip
.
为此,我们首先需要访问virtualenv
命令。 我们可以使用pip
安装它。
If you are using Python 3, upgrade pip
and install the package by typing:
如果您使用的是Python 3 ,请输入以下命令升级pip
并安装软件包:
- sudo -H pip3 install --upgrade pip sudo -H pip3安装--upgrade pip
- sudo -H pip3 install virtualenv 须藤-H pip3 install virtualenv
If you are using Python 2, upgrade pip
and install the package by typing:
如果您使用的是Python 2 ,请输入以下命令升级pip
并安装软件包:
- sudo -H pip install --upgrade pip sudo -H pip install-升级pip
- sudo -H pip install virtualenv 须藤-H pip install virtualenv
With virtualenv
installed, we can start forming our project. Create and move into a directory where we can keep our project files:
安装virtualenv
,我们就可以开始形成我们的项目了。 创建并移至一个目录,我们可以在其中保存项目文件:
mkdir ~/myprojectdir
mkdir〜/ myprojectdir
cd ~/myprojectdir
cd〜/ myprojectdir
Within the project directory, create a Python virtual environment by typing:
在项目目录中,通过键入以下内容来创建Python虚拟环境:
virtualenv myprojectenv
的virtualenv myprojectenv
This will create a directory called myprojectenv
within your myprojectdir
directory. Inside, it will install a local version of Python and a local version of pip
. We can use this to install and configure an isolated Python environment for our project.
这将创建一个名为myprojectenv
你的内myprojectdir
目录。 在内部,它将安装Python的本地版本和pip
的本地版本。 我们可以使用它为我们的项目安装和配置一个隔离的Python环境。
Before we install our project’s Python requirements, we need to activate the virtual environment. You can do that by typing:
在安装项目的Python要求之前,我们需要激活虚拟环境。 您可以通过输入以下内容来实现:
source myprojectenv/bin/activate
源myprojectenv / bin / activate
Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (myprojectenv)user@host:~/myprojectdir$
.
您的提示应更改为指示您现在在Python虚拟环境中进行操作。 它看起来像这样: ( myprojectenv ) user @ host :~/ myprojectdir $
。
With your virtual environment active, install Django, Gunicorn, and the psycopg2
PostgreSQL adaptor with the local instance of pip
:
在您的虚拟环境处于活动状态的情况下,使用本地pip
实例安装Django,Gunicorn和psycopg2
PostgreSQL适配器:
Note: When the virtual environment is activated (when your prompt has (myprojectenv)
preceding it), use pip
instead of pip3
, even if you are using Python 3. The virtual environment’s copy of the tool is always named pip
, regardless of the Python version.
注意:激活虚拟环境后(当提示符之前带有(myprojectenv)
提示时(myprojectenv)
,即使使用的是Python 3,也要使用pip
而不是pip3
。该虚拟环境的工具副本始终命名为pip
,而与Python无关版。
- pip install django gunicorn psycopg2-binary pip安装django gunicorn psycopg2-binary
You should now have all of the software needed to start a Django project.
现在,您应该拥有启动Django项目所需的所有软件。
创建和配置新的Django项目 (Creating and Configuring a New Django Project)
With our Python components installed, we can create the actual Django project files.
安装我们的Python组件后,我们可以创建实际的Django项目文件。
创建Django项目 (Creating the Django Project)
Since we already have a project directory, we will tell Django to install the files here. It will create a second level directory with the actual code, which is normal, and place a management script in this directory. The key to this is that we are defining the directory explicitly instead of allowing Django to make decisions relative to our current directory:
由于我们已经有一个项目目录,因此我们将告诉Django在此处安装文件。 它将使用正常的代码创建第二级目录,并将其放置在该目录中。 这样做的关键是我们正在明确定义目录,而不是允许Django相对于当前目录做出决定:
django-admin.py startproject myproject ~/myprojectdir
django-admin.py startproject myproject〜 / myprojectdir
At this point, your project directory (~/myprojectdir
in our case) should have the following content:
此时,您的项目目录(在本例中为~/ myprojectdir
)应具有以下内容:
~/myprojectdir/manage.py
: A Django project management script.~/myprojectdir/manage.py
项目管理脚本。~/myprojectdir/myproject/
: The Django project package. This should contain the__init__.py
,settings.py
,urls.py
,asgi.py
, andwsgi.py
files.~/myprojectdir/myproject/
:Django项目包。 这应该包含__init__.py
.asgi.py
,settings.py
,urls.py
,asgi.py
和wsgi.py
文件。~/myprojectdir/myprojectenv/
: The virtual environment directory we created earlier.~/myprojectdir/myprojectenv/
:我们之前创建的虚拟环境目录。
调整项目设置 (Adjusting the Project Settings)
The first thing we should do with our newly created project files is adjust the settings. Open the settings file in your text editor:
我们对新创建的项目文件应该做的第一件事是调整设置。 在文本编辑器中打开设置文件:
nano ~/myprojectdir/myproject/settings.py
纳米〜/ myprojectdir / myproject /settings.py
Start by locating the ALLOWED_HOSTS
directive. This defines a list of the server’s addresses or domain names may be used to connect to the Django instance. Any incoming requests with a Host header that is not in this list will raise an exception. Django requires that you set this to prevent a certain class of security vulnerability.
首先找到ALLOWED_HOSTS
指令。 这定义了服务器地址或域名的列表,可用于连接到Django实例。 带有不在此列表中的Host标头的任何传入请求都将引发异常。 Django要求您对此进行设置,以防止出现某类安全漏洞。
In the square brackets, list the IP addresses or domain names that are associated with your Django server. Each item should be listed in quotations with entries separated by a comma. If you wish requests for an entire domain and any subdomains, prepend a period to the beginning of the entry. In the snippet below, there are a few commented out examples used to demonstrate:
在方括号中,列出与Django服务器关联的IP地址或域名。 每个项目都应以引号列出,各条目之间用逗号分隔。 如果希望请求整个域和任何子域,请在条目的开头加上句点。 在以下代码段中,有一些注释掉的示例用于演示:
Note: Be sure to include localhost
as one of the options since we will be proxying connections through a local Nginx instance.
注意:请确保包括localhost
作为选项之一,因为我们将通过本地Nginx实例代理连接。
. . .
# The simplest case: just add the domain name(s) and IP addresses of your Django server
# ALLOWED_HOSTS = [ 'example.com', '203.0.113.5']
# To respond to 'example.com' and any subdomains, start the domain with a dot
# ALLOWED_HOSTS = ['.example.com', '203.0.113.5']
ALLOWED_HOSTS = ['your_server_domain_or_IP', 'second_domain_or_IP', . . ., 'localhost']
Next, find the section that configures database access. It will start with DATABASES
. The configuration in the file is for a SQLite database. We already created a PostgreSQL database for our project, so we need to adjust the settings.
接下来,找到配置数据库访问的部分。 它将以DATABASES
开头。 该文件中的配置适用于SQLite数据库。 我们已经为我们的项目创建了一个PostgreSQL数据库,因此我们需要调整设置。
Change the settings with your PostgreSQL database information. We tell Django to use the psycopg2
adaptor we installed with pip
. We need to give the database name, the database username, the database user’s password, and then specify that the database is located on the local computer. You can leave the PORT
setting as an empty string:
使用PostgreSQL数据库信息更改设置。 我们告诉Django使用与pip
安装的psycopg2
适配器。 我们需要提供数据库名称,数据库用户名,数据库用户的密码,然后指定数据库位于本地计算机上。 您可以将PORT
设置保留为空字符串:
. . .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myproject',
'USER': 'myprojectuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
. . .
Next, move down to the bottom of the file and add a setting indicating where the static files should be placed. This is necessary so that Nginx can handle requests for these items. The following line tells Django to place them in a directory called static
in the base project directory:
接下来,向下移动到文件底部,并添加一个指示应将静态文件放置在何处的设置。 这是必需的,以便Nginx可以处理对这些项目的请求。 以下行告诉Django将它们放置在基础项目目录中名为static
的目录中:
. . .
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
Save and close the file when you are finished.
完成后保存并关闭文件。
完成初始项目设置 (Completing Initial Project Setup)
Now, we can migrate the initial database schema to our PostgreSQL database using the management script:
现在,我们可以使用管理脚本将初始数据库架构迁移到PostgreSQL数据库:
~/myprojectdir/manage.py makemigrations
〜/ myprojectdir /manage.py makemigrations
~/myprojectdir/manage.py migrate
〜/ myprojectdir /manage.py迁移
Create an administrative user for the project by typing:
通过键入以下内容为项目创建一个管理用户:
~/myprojectdir/manage.py createsuperuser
〜/ myprojectdir /manage.py createsuperuser
You will have to select a username, provide an email address, and choose and confirm a password.
您将必须选择一个用户名,提供一个电子邮件地址,然后选择并确认密码。
We can collect all of the static content into the directory location we configured by typing:
我们可以通过输入以下内容将所有静态内容收集到我们配置的目录位置中:
~/myprojectdir/manage.py collectstatic
〜/ myprojectdir /manage.py collectstatic
You will have to confirm the operation. The static files will then be placed in a directory called static
within your project directory.
您必须确认操作。 然后,静态文件将放置在项目目录中名为static
的目录中。
If you followed the initial server setup guide, you should have a UFW firewall protecting your server. In order to test the development server, we’ll have to allow access to the port we’ll be using.
如果您遵循初始服务器设置指南,则应该具有UFW防火墙来保护服务器。 为了测试开发服务器,我们必须允许访问将要使用的端口。
Create an exception for port 8000 by typing:
通过键入以下内容为端口8000创建一个例外:
- sudo ufw allow 8000 sudo ufw允许8000
Finally, you can test our your project by starting up the Django development server with this command:
最后,您可以使用以下命令启动Django开发服务器,以测试我们的项目:
~/myprojectdir/manage.py runserver 0.0.0.0:8000
〜/ myprojectdir /manage.py运行服务器0.0.0.0:8000
In your web browser, visit your server’s domain name or IP address followed by :8000
:
在您的Web浏览器中,访问服务器的域名或IP地址,后跟:8000
:
http://server_domain_or_IP:8000
You should receive the default Django index page:
您应该收到默认的Django索引页:
If you append /admin
to the end of the URL in the address bar, you will be prompted for the administrative username and password you created with the createsuperuser
command:
如果将/admin
附加到地址栏中URL的末尾,将提示您输入使用createsuperuser
命令创建的管理用户名和密码:
After authenticating, you can access the default Django admin interface:
验证之后,您可以访问默认的Django管理界面:
When you are finished exploring, hit CTRL-C in the terminal window to shut down the development server.
探索完成后,请在终端窗口中按CTRL-C以关闭开发服务器。
测试Gunicorn服务项目的能力 (Testing Gunicorn’s Ability to Serve the Project)
The last thing we want to do before leaving our virtual environment is test Gunicorn to make sure that it can serve the application. We can do this by entering our project directory and using gunicorn
to load the project’s WSGI module:
离开虚拟环境之前,我们要做的最后一件事是测试Gunicorn,以确保它可以为应用程序提供服务。 我们可以通过输入项目目录并使用gunicorn
来加载项目的WSGI模块来做到这一点:
cd ~/myprojectdir
cd〜/ myprojectdir
gunicorn --bind 0.0.0.0:8000 myproject.wsgi
古尼康--bind 0.0.0.0:8000 myproject .wsgi
This will start Gunicorn on the same interface that the Django development server was running on. You can go back and test the app again.
这将在运行Django开发服务器的同一界面上启动Gunicorn。 您可以返回并再次测试该应用。
Note: The admin interface will not have any of the styling applied since Gunicorn does not know how to find the static CSS content responsible for this.
注意:由于Gunicorn不知道如何找到负责此操作的静态CSS内容,因此管理界面将不会应用任何样式。
We passed Gunicorn a module by specifying the relative directory path to Django’s wsgi.py
file, which is the entry point to our application, using Python’s module syntax. Inside of this file, a function called application
is defined, which is used to communicate with the application. To learn more about the WSGI specification, click here.
我们通过使用Python的模块语法指定Django的wsgi.py
文件的相对目录路径(这是我们应用程序的入口点)来为wsgi.py
模块。 在此文件内部,定义了一个名为application
的函数,该函数用于与该应用程序进行通信。 要了解有关WSGI规范的更多信息,请单击此处 。
When you are finished testing, hit CTRL-C in the terminal window to stop Gunicorn.
完成测试后,在终端窗口中按CTRL-C停止Gunicorn。
We’re now finished configuring our Django application. We can back out of our virtual environment by typing:
现在,我们完成了Django应用程序的配置。 我们可以通过键入以下内容退出虚拟环境:
- deactivate 停用
The virtual environment indicator in your prompt will be removed.
提示中的虚拟环境指示器将被删除。
为Gunicorn创建systemd套接字和服务文件 (Creating systemd Socket and Service Files for Gunicorn)
We have tested that Gunicorn can interact with our Django application, but we should implement a more robust way of starting and stopping the application server. To accomplish this, we’ll make systemd service and socket files.
我们已经测试了Gunicorn可以与我们的Django应用程序交互,但是我们应该实现一种更可靠的启动和停止应用程序服务器的方式。 为此,我们将制作systemd服务和套接字文件。
The Gunicorn socket will be created at boot and will listen for connections. When a connection occurs, systemd will automatically start the Gunicorn process to handle the connection.
Gunicorn套接字将在启动时创建,并监听连接。 发生连接时,systemd将自动启动Gunicorn进程以处理连接。
Start by creating and opening a systemd socket file for Gunicorn with sudo
privileges:
首先创建并打开具有sudo
权限的Gunicorn的systemd套接字文件:
- sudo nano /etc/systemd/system/gunicorn.socket 须藤纳米/etc/systemd/system/gunicorn.socket
Inside, we will create a [Unit]
section to describe the socket, a [Socket]
section to define the socket location, and an [Install]
section to make sure the socket is created at the right time:
在内部,我们将创建一个[Unit]
节来描述套接字,一个[Socket]
节来定义套接字位置,并创建一个[Install]
节以确保在正确的时间创建了套接字:
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
Save and close the file when you are finished.
完成后保存并关闭文件。
Next, create and open a systemd service file for Gunicorn with sudo
privileges in your text editor. The service filename should match the socket filename with the exception of the extension:
接下来,在您的文本编辑器中创建并使用sudo
权限打开Gunicorn的systemd服务文件。 服务文件名应与套接字文件名匹配,但扩展名除外:
- sudo nano /etc/systemd/system/gunicorn.service 须藤纳米/etc/systemd/system/gunicorn.service
Start with the [Unit]
section, which is used to specify metadata and dependencies. We’ll put a description of our service here and tell the init system to only start this after the networking target has been reached. Because our service relies on the socket from the socket file, we need to include a Requires
directive to indicate that relationship:
从[Unit]
部分开始,该部分用于指定元数据和相关性。 我们将在此处对服务进行描述,并告诉init系统仅在达到网络目标后才启动此服务。 因为我们的服务依赖于套接字文件中的套接字,所以我们需要包含一个Requires
指令来指示这种关系:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
Next, we’ll open up the [Service]
section. We’ll specify the user and group that we want to process to run under. We will give our regular user account ownership of the process since it owns all of the relevant files. We’ll give group ownership to the www-data
group so that Nginx can communicate easily with Gunicorn.
接下来,我们将打开[Service]
部分。 我们将指定要处理的用户和组。 由于该过程拥有所有相关文件,因此我们将授予该过程的常规用户帐户所有权。 我们会将组所有权赋予www-data
组,以便Nginx可以轻松地与Gunicorn通信。
We’ll then map out the working directory and specify the command to use to start the service. In this case, we’ll have to specify the full path to the Gunicorn executable, which is installed within our virtual environment. We will bind the process to the Unix socket we created within the /run
directory so that the process can communicate with Nginx. We log all data to standard output so that the journald
process can collect the Gunicorn logs. We can also specify any optional Gunicorn tweaks here. For example, we specified 3 worker processes in this case:
然后,我们将映射出工作目录并指定用于启动服务的命令。 在这种情况下,我们必须指定Gunicorn可执行文件的完整路径,该路径已安装在虚拟环境中。 我们会将进程绑定到在/run
目录中创建的Unix套接字,以便进程可以与Nginx通信。 我们将所有数据记录到标准输出,以便journald
处理可以收集journald
日志。 我们还可以在此处指定任何可选的Gunicorn调整项。 例如,在这种情况下,我们指定了3个工作进程:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
myproject.wsgi:application
Finally, we’ll add an [Install]
section. This will tell systemd what to link this service to if we enable it to start at boot. We want this service to start when the regular multi-user system is up and running:
最后,我们将添加一个[Install]
部分。 如果我们启用该服务以在启动时启动,它将告诉systemd该服务链接到什么。 我们希望该服务在常规多用户系统启动并运行时启动:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
myproject.wsgi:application
[Install]
WantedBy=multi-user.target
With that, our systemd service file is complete. Save and close it now.
这样,我们的systemd服务文件就完成了。 立即保存并关闭。
We can now start and enable the Gunicorn socket. This will create the socket file at /run/gunicorn.sock
now and at boot. When a connection is made to that socket, systemd will automatically start the gunicorn.service
to handle it:
现在,我们可以启动并启用Gunicorn套接字。 现在将在启动时在/run/gunicorn.sock
处创建套接字文件。 与该套接字建立连接后,systemd将自动启动gunicorn.service
来处理它:
- sudo systemctl start gunicorn.socket sudo systemctl启动gunicorn.socket
- sudo systemctl enable gunicorn.socket sudo systemctl启用gunicorn.socket
We can confirm that the operation was successful by checking for the socket file.
我们可以通过检查套接字文件来确认操作成功。
检查Gunicorn套接字文件 (Checking for the Gunicorn Socket File)
Check the status of the process to find out whether it was able to start:
检查进程的状态,以了解它是否能够启动:
- sudo systemctl status gunicorn.socket sudo systemctl状态gunicorn.socket
You should receive an output like this:
您应该收到如下输出:
Output
● gunicorn.socket - gunicorn socket
Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor prese>
Active: active (listening) since Fri 2020-06-26 17:53:10 UTC; 14s ago
Triggers: ● gunicorn.service
Listen: /run/gunicorn.sock (Stream)
Tasks: 0 (limit: 1137)
Memory: 0B
CGroup: /system.slice/gunicorn.socket
Next, check for the existence of the gunicorn.sock
file within the /run
directory:
接下来,检查/run
目录中是否存在gunicorn.sock
文件:
- file /run/gunicorn.sock 文件/run/gunicorn.sock
Output
/run/gunicorn.sock: socket
If the systemctl status
command indicated that an error occurred or if you do not find the gunicorn.sock
file in the directory, it’s an indication that the Gunicorn socket was not able to be created correctly. Check the Gunicorn socket’s logs by typing:
如果systemctl status
命令指示发生错误,或者在目录中找不到gunicorn.sock
文件,则表明无法正确创建Gunicorn套接字。 通过键入以下内容来检查Gunicorn套接字的日志:
- sudo journalctl -u gunicorn.socket 须藤journalctl -u gunicorn.socket
Take another look at your /etc/systemd/system/gunicorn.socket
file to fix any problems before continuing.
在继续操作之前,请先查看您的/etc/systemd/system/gunicorn.socket
文件以解决所有问题。
测试套接字激活 (Testing Socket Activation)
Currently, if you’ve only started the gunicorn.socket
unit, the gunicorn.service
will not be active yet since the socket has not yet received any connections. You can check this by typing:
当前,如果您只启动了gunicorn.socket
单元,由于套接字尚未收到任何连接,因此gunicorn.service
将不会处于活动状态。 您可以通过输入以下内容进行检查:
- sudo systemctl status gunicorn sudo systemctl状态古尼康
Output
● gunicorn.service - gunicorn daemon
Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled)
Active: inactive (dead)
To test the socket activation mechanism, we can send a connection to the socket through curl
by typing:
为了测试套接字激活机制,我们可以通过输入以下内容通过curl
将连接发送到套接字:
- curl --unix-socket /run/gunicorn.sock localhost curl --unix-socket /run/gunicorn.sock本地主机
You should receive the HTML output from your application in the terminal. This indicates that Gunicorn was started and was able to serve your Django application. You can verify that the Gunicorn service is running by typing:
您应该从终端中的应用程序接收HTML输出。 这表明Gunicorn已启动,并且能够为您的Django应用程序提供服务。 您可以通过键入以下命令来验证Gunicorn服务是否正在运行:
- sudo systemctl status gunicorn sudo systemctl状态古尼康
Output
● gunicorn.service - gunicorn daemon
Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled)
Active: active (running) since Fri 2020-06-26 18:52:21 UTC; 2s ago
TriggeredBy: ● gunicorn.socket
Main PID: 22914 (gunicorn)
Tasks: 4 (limit: 1137)
Memory: 89.1M
CGroup: /system.slice/gunicorn.service
├─22914 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico>
├─22927 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico>
├─22928 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico>
└─22929 /home/sammy/myprojectdir/myprojectenv/bin/python /home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunico>
Jun 26 18:52:21 django-tutorial systemd[1]: Started gunicorn daemon.
Jun 26 18:52:21 django-tutorial gunicorn[22914]: [2020-06-26 18:52:21 +0000] [22914] [INFO] Starting gunicorn 20.0.4
Jun 26 18:52:21 django-tutorial gunicorn[22914]: [2020-06-26 18:52:21 +0000] [22914] [INFO] Listening at: unix:/run/gunicorn.sock (22914)
Jun 26 18:52:21 django-tutorial gunicorn[22914]: [2020-06-26 18:52:21 +0000] [22914] [INFO] Using worker: sync
Jun 26 18:52:21 django-tutorial gunicorn[22927]: [2020-06-26 18:52:21 +0000] [22927] [INFO] Booting worker with pid: 22927
Jun 26 18:52:21 django-tutorial gunicorn[22928]: [2020-06-26 18:52:21 +0000] [22928] [INFO] Booting worker with pid: 22928
Jun 26 18:52:21 django-tutorial gunicorn[22929]: [2020-06-26 18:52:21 +0000] [22929] [INFO] Booting worker with pid: 22929
If the output from curl
or the output of systemctl status
indicates that a problem occurred, check the logs for additional details:
如果curl
的输出或systemctl status
的输出指示发生问题,请检查日志以获取其他详细信息:
- sudo journalctl -u gunicorn 须藤journalctl -u gunicorn
Check your /etc/systemd/system/gunicorn.service
file for problems. If you make changes to the /etc/systemd/system/gunicorn.service
file, reload the daemon to reread the service definition and restart the Gunicorn process by typing:
检查/etc/systemd/system/gunicorn.service
文件中的问题。 如果您对/etc/systemd/system/gunicorn.service
文件进行了更改,请重新加载守护程序以重新读取服务定义并通过键入以下命令重新启动Gunicorn进程:
- sudo systemctl daemon-reload sudo systemctl守护进程重新加载
- sudo systemctl restart gunicorn sudo systemctl重新启动gunicorn
Make sure you troubleshoot the above issues before continuing.
在继续操作之前,请确保对以上问题进行故障排除。
配置Nginx代理传递给Gunicorn (Configure Nginx to Proxy Pass to Gunicorn)
Now that Gunicorn is set up, we need to configure Nginx to pass traffic to the process.
现在已经建立了Gunicorn,我们需要配置Nginx来将流量传递给该进程。
Start by creating and opening a new server block in Nginx’s sites-available
directory:
首先在Nginx的sites-available
目录中创建并打开一个新的服务器块:
sudo nano /etc/nginx/sites-available/myproject
须藤纳米/ etc / nginx / sites-available / myproject
Inside, open up a new server block. We will start by specifying that this block should listen on the normal port 80 and that it should respond to our server’s domain name or IP address:
在内部,打开一个新的服务器块。 我们将首先指定此块应在普通端口80上侦听,并且应响应我们服务器的域名或IP地址:
server {
listen 80;
server_name server_domain_or_IP;
}
Next, we will tell Nginx to ignore any problems with finding a favicon. We will also tell it where to find the static assets that we collected in our ~/myprojectdir/static
directory. All of these files have a standard URI prefix of “/static”, so we can create a location block to match those requests:
接下来,我们将告诉Nginx忽略查找收藏夹图标的任何问题。 我们还将告诉它在哪里找到在~/ myprojectdir /static
目录中收集的静态资产。 所有这些文件的标准URI前缀均为“ / static”,因此我们可以创建一个位置块来匹配这些请求:
server {
listen 80;
server_name server_domain_or_IP;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/sammy/myprojectdir;
}
}
Finally, we’ll create a location / {}
block to match all other requests. Inside of this location, we’ll include the standard proxy_params
file included with the Nginx installation and then we will pass the traffic directly to the Gunicorn socket:
最后,我们将创建一个location / {}
块以匹配所有其他请求。 在此位置的内部,我们将包括Nginx安装中包含的标准proxy_params
文件,然后将流量直接传递到Gunicorn套接字:
server {
listen 80;
server_name server_domain_or_IP;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/sammy/myprojectdir;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
Save and close the file when you are finished. Now, we can enable the file by linking it to the sites-enabled
directory:
完成后保存并关闭文件。 现在,我们可以通过将文件链接到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
Test your Nginx configuration for syntax errors by typing:
通过键入以下内容来测试Nginx配置是否存在语法错误:
- sudo nginx -t 须藤Nginx -t
If no errors are reported, go ahead and restart Nginx by typing:
如果未报告任何错误,请继续并通过键入以下命令重新启动Nginx:
- sudo systemctl restart nginx sudo systemctl重启nginx
Finally, we need to open up our firewall to normal traffic on port 80. Since we no longer need access to the development server, we can remove the rule to open port 8000 as well:
最后,我们需要为端口80上的正常流量打开防火墙。由于我们不再需要访问开发服务器,因此我们也可以删除打开端口8000的规则:
- sudo ufw delete allow 8000 sudo ufw删除允许8000
- sudo ufw allow 'Nginx Full' sudo ufw允许'Nginx Full'
You should now be able to go to your server’s domain or IP address to view your application.
现在,您应该能够访问服务器的域或IP地址来查看您的应用程序。
Note: After configuring Nginx, the next step should be securing traffic to the server using SSL/TLS. This is important because without it, all information, including passwords are sent over the network in plain text.
注意:配置Nginx之后,下一步应该是使用SSL / TLS保护到服务器的流量。 这很重要,因为没有它,所有信息(包括密码)都将以纯文本格式通过网络发送。
If you have a domain name, the easiest way to get an SSL certificate to secure your traffic is using Let’s Encrypt. Follow this guide to set up Let’s Encrypt with Nginx on Ubuntu 20.04. Follow the procedure using the Nginx server block we created in this guide.
如果您拥有域名,那么获取SSL证书以保护流量的最简单方法是使用“加密”。 按照本指南在Ubuntu 20.04上设置“使用Nginx加密”。 使用我们在本指南中创建的Nginx服务器块按照该过程进行操作。
对Nginx和Gunicorn进行故障排除 (Troubleshooting Nginx and Gunicorn)
If this last step does not show your application, you will need to troubleshoot your installation.
如果最后一步没有显示您的应用程序,则需要对安装进行故障排除。
Nginx显示默认页面而不是Django应用程序 (Nginx Is Showing the Default Page Instead of the Django Application)
If Nginx displays the default page instead of proxying to your application, it usually means that you need to adjust the server_name
within the /etc/nginx/sites-available/myproject
file to point to your server’s IP address or domain name.
如果Nginx显示默认页面而不是代理到您的应用程序,则通常意味着您需要调整/etc/nginx/sites-available/ myproject
文件中的server_name
以指向服务器的IP地址或域名。
Nginx uses the server_name
to determine which server block to use to respond to requests. If you receive the default Nginx page, it is a sign that Nginx wasn’t able to match the request to a sever block explicitly, so it’s falling back on the default block defined in /etc/nginx/sites-available/default
.
Nginx使用server_name
确定使用哪个服务器块来响应请求。 如果收到默认的Nginx页面,则表明Nginx无法将请求明确匹配到服务器块,因此它会退回到/etc/nginx/sites-available/default
定义的默认块。
The server_name
in your project’s server block must be more specific than the one in the default server block to be selected.
项目服务器块中的server_name
必须比要选择的默认服务器块中的server_name
更具体。
Nginx显示502 Bad Gateway错误,而不是Django应用程序 (Nginx Is Displaying a 502 Bad Gateway Error Instead of the Django Application)
A 502 error indicates that Nginx is unable to successfully proxy the request. A wide range of configuration problems express themselves with a 502 error, so more information is required to troubleshoot properly.
502错误表示Nginx无法成功代理请求。 各种各样的配置问题都以502错误表示,因此需要更多信息以进行适当的故障排除。
The primary place to look for more information is in Nginx’s error logs. Generally, this will tell you what conditions caused problems during the proxying event. Follow the Nginx error logs by typing:
寻找更多信息的主要地方是在Nginx的错误日志中。 通常,这将告诉您什么情况导致代理事件期间出现问题。 通过输入以下内容来关注Nginx错误日志:
- sudo tail -F /var/log/nginx/error.log 须藤尾-F /var/log/nginx/error.log
Now, make another request in your browser to generate a fresh error (try refreshing the page). You should receive a fresh error message written to the log. If you look at the message, it should help you narrow down the problem.
现在,在浏览器中再次发出请求以生成新的错误(尝试刷新页面)。 您应该会收到一条新的错误消息,将其写入日志。 如果您查看该消息,它应该可以帮助您缩小问题范围。
You might receive the following message:
您可能会收到以下消息:
connect() to unix:/run/gunicorn.sock failed (2: No such file or directory)
connect()到unix:/run/gunicorn.sock失败(2:没有这样的文件或目录)
This indicates that Nginx was unable to find the gunicorn.sock
file at the given location. You should compare the proxy_pass
location defined within /etc/nginx/sites-available/myproject
file to the actual location of the gunicorn.sock
file generated by the gunicorn.socket
systemd unit.
这表明Nginx无法在给定位置找到gunicorn.sock
文件。 您应该将/etc/nginx/sites-available/myproject
文件中定义的proxy_pass
位置与gunicorn.socket
系统单元生成的gunicorn.sock
文件的实际位置进行gunicorn.sock
。
If you cannot find a gunicorn.sock
file within the /run
directory, it generally means that the systemd socket file was unable to create it. Go back to the section on checking for the Gunicorn socket file to step through the troubleshooting steps for Gunicorn.
如果在/run
目录中找不到gunicorn.sock
文件,则通常意味着systemd套接字文件无法创建它。 返回有关检查Gunicorn套接字文件的部分,以逐步完成Gunicorn的故障排除步骤。
connect() to unix:/run/gunicorn.sock failed (13: Permission denied)
connect()到unix:/run/gunicorn.sock失败(13:权限被拒绝)
This indicates that Nginx was unable to connect to the Gunicorn socket because of permissions problems. This can happen when the procedure is followed using the root user instead of a sudo
user. While systemd is able to create the Gunicorn socket file, Nginx is unable to access it.
这表明由于权限问题,Nginx无法连接到Gunicorn套接字。 当使用root用户而不是sudo
用户执行该过程时,可能会发生这种情况。 虽然systemd可以创建Gunicorn套接字文件,但Nginx无法访问它。
This can happen if there are limited permissions at any point between the root directory (/
) the gunicorn.sock
file. We can review the permissions and ownership values of the socket file and each of its parent directories by passing the absolute path to our socket file to the namei
command:
如果有在根目录(之间的任何点有限的权限就会发生这种情况/
)的gunicorn.sock
文件。 通过将套接字文件的绝对路径传递给namei
命令,我们可以查看套接字文件及其每个父目录的权限和所有权值:
- namei -l /run/gunicorn.sock 名称-l /run/gunicorn.sock
Output
f: /run/gunicorn.sock
drwxr-xr-x root root /
drwxr-xr-x root root run
srw-rw-rw- root root gunicorn.sock
The output displays the permissions of each of the directory components. By looking at the permissions (first column), owner (second column) and group owner (third column), we can figure out what type of access is allowed to the socket file.
输出显示每个目录组件的权限。 通过查看权限(第一列),所有者(第二列)和组所有者(第三列),我们可以确定允许对套接字文件进行哪种类型的访问。
In the above example, the socket file and each of the directories leading up to the socket file have world read and execute permissions (the permissions column for the directories end with r-x
instead of ---
). The Nginx process should be able to access the socket successfully.
在上面的示例中,套接字文件和通向该套接字文件的每个目录都具有全局读取和执行权限(目录的权限列以rx
而不是---
结尾)。 Nginx进程应该能够成功访问套接字。
If any of the directories leading up to the socket do not have world read and execute permission, Nginx will not be able to access the socket without allowing world read and execute permissions or making sure group ownership is given to a group that Nginx is a part of.
如果导致套接字的任何目录都不具有世界范围的读取和执行许可权,则Nginx将无法访问套接字,而无需允许世界范围的读取和执行许可权或确保将组所有权授予了Nginx参与其中的组的。
Django正在显示:“无法连接到服务器:连接被拒绝” (Django Is Displaying: “could not connect to server: Connection refused”)
One message that you may receive from Django when attempting to access parts of the application in the web browser is:
尝试在Web浏览器中访问应用程序的某些部分时,您可能会从Django收到一条消息:
OperationalError at /admin/login/
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
This indicates that Django is unable to connect to the Postgres database. Make sure that the Postgres instance is running by typing:
这表明Django无法连接到Postgres数据库。 通过键入以下命令来确保Postgres实例正在运行:
- sudo systemctl status postgresql sudo systemctl状态PostgreSQL
If it is not, you can start it and enable it to start automatically at boot (if it is not already configured to do so) by typing:
如果不是,您可以通过键入以下内容来启动它并使它在引导时自动启动(如果尚未配置):
- sudo systemctl start postgresql sudo systemctl启动PostgreSQL
- sudo systemctl enable postgresql sudo systemctl启用PostgreSQL
If you are still having issues, make sure the database settings defined in the ~/myprojectdir/myproject/settings.py
file are correct.
如果仍然有问题,请确保~/myprojectdir/myproject/settings.py
文件中定义的数据库设置正确。
进一步的故障排除 (Further Troubleshooting)
For additional troubleshooting, the logs can help narrow down root causes. Check each of them in turn and look for messages indicating problem areas.
对于其他故障排除,日志可以帮助缩小根本原因。 依次检查它们中的每一个,并查找指示问题区域的消息。
The following logs may be helpful:
以下日志可能会有所帮助:
Check the Nginx process logs by typing:
sudo journalctl -u nginx
通过键入以下
sudo journalctl -u nginx
检查Nginx进程日志:sudo journalctl -u nginx
Check the Nginx access logs by typing:
sudo less /var/log/nginx/access.log
通过键入以下
sudo less /var/log/nginx/access.log
检查Nginx访问日志:sudo less /var/log/nginx/access.log
Check the Nginx error logs by typing:
sudo less /var/log/nginx/error.log
通过键入以下
sudo less /var/log/nginx/error.log
检查Nginx错误日志:sudo less /var/log/nginx/error.log
Check the Gunicorn application logs by typing:
sudo journalctl -u gunicorn
通过输入以下
sudo journalctl -u gunicorn
应用程序日志:sudo journalctl -u gunicorn
Check the Gunicorn socket logs by typing:
sudo journalctl -u gunicorn.socket
通过输入以下
sudo journalctl -u gunicorn.socket
套接字日志:sudo journalctl -u gunicorn.socket
As you update your configuration or application, you will likely need to restart the processes to adjust to your changes.
在更新配置或应用程序时,可能需要重新启动过程以适应您的更改。
If you update your Django application, you can restart the Gunicorn process to pick up the changes by typing:
如果更新Django应用程序,则可以通过键入以下内容来重新启动Gunicorn进程以获取更改:
- sudo systemctl restart gunicorn sudo systemctl重新启动gunicorn
If you change Gunicorn socket or service files, reload the daemon and restart the process by typing:
如果更改Gunicorn套接字或服务文件,请重新加载守护程序并通过键入以下内容重新启动该过程:
- sudo systemctl daemon-reload sudo systemctl守护进程重新加载
- sudo systemctl restart gunicorn.socket gunicorn.service sudo systemctl重新启动gunicorn.socket gunicorn.service
If you change the Nginx server block configuration, test the configuration and then Nginx by typing:
如果更改Nginx服务器块配置,请输入以下内容测试配置,然后测试Nginx:
- sudo nginx -t && sudo systemctl restart nginx sudo nginx -t && sudo systemctl重新启动nginx
These commands are helpful for picking up changes as you adjust your configuration.
这些命令有助于您在调整配置时获取更改。
结论 (Conclusion)
In this guide, we’ve set up a Django project in its own virtual environment. We’ve configured Gunicorn to translate client requests so that Django can handle them. Afterwards, we set up Nginx to act as a reverse proxy to handle client connections and serve the correct project depending on the client request.
在本指南中,我们在其自己的虚拟环境中设置了一个Django项目。 我们已经配置了Gunicorn来翻译客户端请求,以便Django可以处理它们。 之后,我们将Nginx设置为反向代理,以处理客户端连接并根据客户端请求提供正确的项目。
Django makes creating projects and applications simple by providing many of the common pieces, allowing you to focus on the unique elements. By leveraging the general tool chain described in this article, you can easily serve the applications you create from a single server.
Django提供了许多常见的部分,使您可以专注于独特的元素,从而使创建项目和应用程序变得简单。 通过利用本文介绍的常规工具链,您可以轻松地为从单个服务器创建的应用程序提供服务。