在Ubuntu 18.04上使用Postgres,Nginx和Gunicorn设置Django

Django is a versatile, powerful, efficient and ever-evolving python-based web application framework that you can use to get your web application up and running. It’s a popular web framework and usually comes with a development server used for locally testing your code. If you intend to push your applications to production, then a more robust and secure web server set up will be required.

Django是一个通用,强大,高效且不断发展的基于python的Web应用程序框架,您可以使用它来启动和运行Web应用程序。 这是一个流行的Web框架,通常带有用于本地测试代码的开发服务器。 如果您打算将应用程序推入生产环境,则将需要更健壮和安全的Web服务器设置。

In this guide, we will take you through the art of professionally deploying and configuring Django in a more efficient and resilient manner. We will install and configure PostgreSQL database in the place of the SQLite database, and integrate the Gunicorn application server which will interface with the applications. Later, we will proceed with setting up the NGINX web server which will provide a reverse proxy channel to the Gunicorn server, thereby providing us with the required performance and security components to serve our applications.

在本指南中,我们将带您以更有效和更具弹性的方式专业部署和配置Django。 我们将在SQLite数据库的位置安装和配置PostgreSQL数据库,并集成将与应用程序交互的Gunicorn应用程序服务器。 稍后,我们将继续设置NGINX Web服务器,它将为Gunicorn服务器提供反向代理通道,从而为我们提供服务于我们的应用程序所需的性能和安全性组件。

先决条件 (Prerequisites)

Before we get started, let’s perform a quick flight check and ensure we have the following

在开始之前,让我们进行一次快速的飞行检查,并确保我们具备以下条件

  • A fresh Ubuntu 18.04 server instance

    新鲜的Ubuntu 18.04服务器实例
  • A non-root user with sudo privileges. In this guide we shall use james

    具有sudo特权的非root用户。 在本指南中,我们将使用james
  • SSH access to the server

    SSH访问服务器

目标 (Objectives)

Here is a quick walkthrough of what we intend to achieve. We are going to install Django within a virtual environment. This allows for projects to be handled separately from the host environment. We shall then embark on installation and configuration of Gunicorn application server which will interface the application and translate requests in HTTP protocol to Python calls which our application can process. Finally, we will set up Nginx which is a high-performance web server with a myriad of security components which will boost the security of our applications.

这是我们打算实现的目标的快速演练。 我们将在虚拟环境中安装Django。 这允许项目与宿主环境分开处理。 然后,我们将着手Gunicorn应用程序服务器的安装和配置,该服务器将与应用程序接口,并将HTTP协议中的请求转换为我们的应用程序可以处理的Python调用。 最后,我们将设置Nginx,这是一台具有大量安全组件的高性能Web服务器,它将提高我们应用程序的安全性。

入门 (Getting started)

To start off, we will begin by updating our Ubuntu repositories

首先,我们将从更新我们的Ubuntu存储库开始

$ sudo apt-get update

Next, we will download and install the requisite software packages for all the applications we are going to configure. These will include the pip package manager, PostgreSQL, and Nginx.
If you are running Django with Python3, the syntax will be

接下来,我们将为要配置的所有应用程序下载并安装必需的软件包。 这些将包括pip包管理器 ,PostgreSQL和Nginx。
如果您使用Python3运行Django,则语法为

$ sudo apt-get install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx

If your system runs Python2, the command will be:

如果您的系统运行Python2,则命令为:

$ sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx

Sample output

样品输出

The command will install pip package manager, all the necessary Python development files required to build Gunicorn, Nginx web server, Postgres database and the crucial libraries required to interact with the database engine.

该命令将安装pip软件包管理器,构建Gunicorn,Nginx Web服务器,Postgres数据库所需的所有必需的Python开发文件以及与数据库引擎进行交互所需的关键库。

After successful installation of all the required software packages, its time now to create a database and a user for the Django web application

成功安装所有必需的软件包之后,现在该为Django Web应用程序创建数据库和用户了

创建PostgreSQL数据库和数据库用户 (Creating PostgreSQL database and database user )

Let’s now jump right in and create a database and a user for Django application
Log in to Postgres and execute the command

现在让我们直接进入并为Django应用程序创建数据库和用户
登录到Postgres并执行命令

$ sudo -u postgres psql

You will drop to the Postgres prompt as seen in the output

您将进入输出显示的Postgres提示

Create a database for your project. In this case, the database name is “project”.

为您的项目创建一个数据库。 在这种情况下,数据库名称为“项目”。

postgres=# CREATE DATABASE project;

Sample output

样品输出

NOTE! All commands in PostgreSQL need to be terminated with a semi-colon.

注意! PostgreSQL中的所有命令都必须以分号终止。

After successful creation of the database, create a user for the Django project and be sure to assign a secure Password. In this case, the user is projectuser

成功创建数据库后,为Django项目创建一个用户,并确保分配一个安全的密码。 在这种情况下,用户是projectuser

Replace the ‘password’ attribute with your own strong Password.

用您自己的强密码替换“ password”属性。

postgres=# CREATE USER projectuser WITH PASSWORD 'password';

Sample output

样品输出

To confirm to Django’s set up parameters for database connectivity, we are going to:

为了确认Django的数据库连接设置参数,我们将执行以下操作:

  1. Set default encoding to UTF-8

    将默认编码设置为UTF-8
  2. Set isolation scheme to ‘read committed’ value

    将隔离方案设置为“读取已提交”值
  3. Set timezone to UTC

    将时区设置为UTC

Execute the commands below to fulfill the setup requirements

执行以下命令来满足设置要求

postgres=# ALTER ROLE projectuser SET client_encoding TO 'utf8';
postgres=# ALTER ROLE projectuser SET default_transaction_isolation TO 'read committed';
postgres=# ALTER ROLE projectuser SET timezone TO 'UTC';

Let’s now grant database access to our newly created user

现在让我们向新创建的用户授予数据库访问权限

postgres=# GRANT ALL PRIVILEGES ON DATABASE project TO projectuser;

Sample output

样品输出

Now you can exit from the Postgres environment.

现在您可以退出Postgres环境。

postgres=# \q

为您的Django项目创建Python虚拟环境 (Creating a Python Virtual Environment for your Django Project)

For easier management of our application, we are going to install the required Python prerequisites in a virtual environment.
But first, let’s install the virtual environment
If your system is running Python3, upgrade pip by executing

为了更轻松地管理我们的应用程序,我们将在虚拟环境中安装必需的Python先决条件。
但首先,让我们安装虚拟环境
如果您的系统运行的是Python3,请通过执行以下命令来升级pip

$ sudo -H pip3  install --upgrade pip

For a system running on Python2 run

对于在Python2上运行的系统

$ sudo -H pip install --upgrade pip

Sample Output

样本输出

Thereafter, install the virtual environment using pip

之后,使用pip安装虚拟环境

$ sudo -H pip install virtualenv

Sample Output

样本输出

With our virtual environment in place, we are now going to create and move into it

有了我们的虚拟环境,我们现在将创建并迁移到其中

$ mkdir ~/project
$ cd ~/project

Now create a Python virtual environment

现在创建一个Python虚拟环境

virtualenv projectenv

Sample output

样品输出

This creates a directory called projectenv within project directory.

projectenv在项目目录中创建一个名为projectenv目录。

Before installing Python requirements, activate the virtual environment

在安装Python要求之前,请激活虚拟环境

$ source projectenv/bin/activate

Sample output

样品输出

Notice how the prompt changes to (projectenv)james@ubuntu: ~/project$

注意提示如何更改为(projectenv)james@ubuntu: ~/project$

With the virtual environment active, let’s install Gunicorn, Django, and Psycopg2 Postgres adapter using pip.

在激活虚拟环境的情况下,让我们使用pip安装Gunicorn,Django和Psycopg2 Postgres适配器。

$ pip install django gunicorn psycopg2-binary

Sample Output

样本输出

创建和配置新的Django项目 (Creating and configuring a new Django project)

At this point, we shall instruct Django to install project files in the project directory that we already created. A second level directory will be created alongside a management script.
To achieve this execute the command below.

此时,我们将指示Django将项目文件安装在我们已经创建的项目目录中。 将在管理脚本旁边创建第二级目录。
为此,请执行以下命令。

$ django-admin.py startproject project ~/project

Our project directory, in this case, ~/project should have the following contents

我们的项目目录,在这种情况下, ~/project应该具有以下内容

manage.py      -  Django’s Python management script
project             - directory containing Django’s project package
projectenv      - Virtual environment directory that was earlier created

Sample output

样品输出

调整项目文件配置 (Adjusting Project files configuration)

We are going to open the settings file

我们将打开设置文件

vim ~/project/settings.py

Scroll down and be on the lookout for the ‘ALLOWED HOSTS’ attribute. Within the square brackets, specify the server’s IP address and append the ‘localhost’ attribute.

向下滚动并注意“ ALLOWED HOSTS”属性。 在方括号内,指定服务器的IP地址并附加'localhost'属性。

Sample output

样品输出

Next, locate the ‘DATABASES’ section. Adjust the settings to conform to the PostgreSQL database information. This includes the database name, user and password of the user.

接下来,找到“数据库”部分。 调整设置以符合PostgreSQL数据库信息。 这包括数据库名称,用户名和用户密码。

Sample output

样品输出

Next, scroll down and specify the location of the static files. This is important so that Nginx can seamlessly handle requests for these items. From the snippet below, static files will be placed in a directory called ‘static’

接下来,向下滚动并指定静态文件的位置。 这很重要,以便Nginx可以无缝处理对这些项目的请求。 在下面的代码段中,静态文件将放置在名为“ static”的目录中

Save and Exit.

保存并退出。

完成初始项目设置 (Completing initial project setup)

Let us now migrate the database scheme to our PostgreSQL database

现在让我们将数据库方案迁移到PostgreSQL数据库

~/project/manage.py makemigrations

Sample output

样品输出

~/project/manage.py migrate

Sample output

样品输出

 nginx postgres and gunicorn

Next, we are going to create a super user for the Django project by executing the following command


接下来,我们将通过执行以下命令为Django项目创建一个超级用户

~/project/manage.py createsuperuser

You will be prompted for a username, email, password as shown below

系统将提示您输入用户名,电子邮件和密码,如下所示

Sample output

样品输出

Upon successful creation of the superuser, we can now collect static content into the directory location

成功创建超级用户后,我们现在可以将静态内容收集到目录位置中

~/project/manage.py collectstatic

Sample output

样品输出

These static files will be placed in the ‘static’ directory in the project folder.

这些静态文件将放置在项目文件夹的'static'目录中。

To test the development server, we are going to allow a port, in this case, port 8000 which will be used for accessing the application via a web browser.

为了测试开发服务器,我们将允许使用一个端口,在本例中为端口8000,该端口将用于通过Web浏览器访问应用程序。

To open the port, we will execute

要打开端口,我们将执行

sudo ufw allow 8000

Finally, start the Django development server in the virtual environment by running

最后,通过运行以下命令在虚拟环境中启动Django开发服务器:

~/project/manage.py runserver 0.0.0.0:8000

Open your web browser and visit your server’s address

打开网络浏览器并访问服务器的地址

In this case, our server’s address is

在这种情况下,我们服务器的地址是

https://38.76.11.180/

You should be able to see the following Django’s index page

您应该能够看到以下Django的索引页面

Sample output

样品输出

Let’s now append /admin at the end of the URL to get to the login page

现在让我们在URL末尾附加/ admin进入登录页面。

https://38.76.11.180/admin

Sample output

样品输出

Provide the credentials you provided when creating the superuser account and hit ‘Login’

提供您在创建超级用户帐户时提供的凭据,然后单击“登录”

This will take us to the Django’s Admin panel

这将带我们进入Django的管理面板

Sample output

样品输出

Great! Now that we have confirmed that Django is up and running, let’s hit CTRL + C on the terminal to exit the application

大! 现在,我们已经确认Django已启动并正在运行,让我们在终端上按CTRL + C退出应用程序

确认Gunicorn测试项目的能力 (Confirming Gunicorn’s ability to test the Project)

Before exiting the virtual environment, let’s verify that our Gunicorn application server can serve the Django.
While still in the project directory, let’s load the WSGI module

在退出虚拟环境之前,让我们验证我们的Gunicorn应用服务器可以为Django服务。
仍在项目目录中时,让我们加载WSGI模块

gunicorn --bind 0.0.0.0:8000 project.wsgi

This fires up Gunicorn on the same interface and port that the Django server was running on. You can go back and verify that the Django application is running on the web browser.

这会在运行Django服务器的相同接口和端口上启动Gunicorn。 您可以返回并确认Django应用程序正在Web浏览器上运行。

With that done hit CTRL + C to stop the application and run the deactivate command to exit the virtual environment.

完成后,按CTRL + C停止应用程序并运行deactivate命令退出虚拟环境。

Having tested that the Gunicorn application server can serve our Django application, it’s time to implement a more robust avenue of starting and stopping the application server.
We are going to create a systemd service file with Gunicorn using the following command

经过测试,Gunicorn应用程序服务器可以为我们的Django应用程序提供服务,是时候实现一种更强大的启动和停止应用程序服务器的途径了。
我们将使用以下命令使用Gunicorn创建一个systemd服务文件

$ sudo vim /etc/systemd/system/gunicorn.service

Starting with the [Unit] section, paste the following content

从[Unit]部分开始,粘贴以下内容

[Unit]
Description=gunicorn daemon
After=network.target

This section specifies dependencies and metadata

本节指定依赖项和元数据

Next, create the [service] section.

接下来,创建[service]部分。

In this section, we shall specify the user and group that the process should run under. In this case, the user is root and the group is www-data. The group is specified as www-data so that Nginx can seamlessly communicate with Gunicorn.

在本节中,我们将指定进程应在其下运行的用户和组。 在这种情况下,用户为root,而组为www-data。 该组被指定为www-data,以便Nginx可以与Gunicorn无缝通信。

The full path to Gunicorn executable will then be indicated. Since Nginx is installed within the same server, we will bind it to a Unix socket.

然后将显示Gunicorn可执行文件的完整路径。 由于Nginx安装在同一服务器内,因此我们将其绑定到Unix套接字。

Paste the following content

粘贴以下内容

[Service]
User=james
Group=www-data
WorkingDirectory=/home/james/project
ExecStart=/home/james/project/projectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/james/project/project.sock project.wsgi:application

Finally, create [Install] section and append the following lines

最后,创建[Install]部分并添加以下行

[Install]
WantedBy=multi-user.target

Great! Now our systemd service file is complete.

大! 现在我们的系统服务文件已完成。

Save and close the text editor. Restart Gunicorn service and enable it to start on boot

保存并关闭文本编辑器。 重新启动Gunicorn服务,并使其在启动时启动

$ sudo systemctl start gunicorn
$ sudo systemctl enable gunicorn

To check the status of gunicorn run

检查gunicorn运行状态

$ systemctl status gunicorn

Sample output

样品输出

验证是否存在Gunicorn套接字文件 (Verify for the presence of Gunicorn Socket file)

Now that we have verified that Nginx is up and running, let us verify the existence of the project.sock file in our project directory

既然我们已经验证了Nginx已启动并正在运行,那么让我们验证项目目录中是否存在project.sock文件。

$ ls -l /home/james/project

Sample output

样品输出

NOTE:

注意:

If project.sock file is missing, this is an indicator that gunicorn was not able to start correctly.
Additionally, you can check the gunicorn logs by executing the command below

如果缺少project.sock文件,则表明gunicorn无法正确启动。
另外,您可以通过执行以下命令来检查Gunicorn日志

$ sudo journalctl -u gunicorn

There are a number of reasons why Nginx could not have created the project.sock file. Some include

Nginx无法创建project.sock文件的原因有很多。 一些包括

  1. Project files being owned by root user instead of sudo user

    项目文件由root用户而非sudo用户拥有
  2. The working directory within the /etc/systemd/system/gunicorn.service not pointing to the project directory.

    /etc/systemd/system/gunicorn.service的工作目录未指向项目目录。
  3. Incorrect configurations in the ExecStart directive

    ExecStart指令中的配置不正确

If all configurations are okay, then you should not get any errors after running

如果所有配置都可以,那么运行后应该不会出现任何错误

$ sudo journalctl -u gunicorn

Once you make changes to the /etc/systemd/system/gunicorn.service file, ensure that you reload the daemon service for the changes to take effect

/etc/systemd/system/gunicorn.service文件进行更改后,请确保重新加载守护程序服务以使更改生效

$ sudo systemctl daemon-reload

$ sudo systemctl restart gunicorn

Configuring Nginx to direct traffic to Gunicorn

配置Nginx以将流量定向到Gunicorn

The last phase in this guide is configuring Nginx web server to channel web traffic to Gunicorn service

本指南的最后一个阶段是配置Nginx Web服务器以将Web流量引导到Gunicorn服务

We shall create and open a new server block in sites-available directory

我们将在sites-available目录中创建并打开一个新的服务器块

$ sudo vim /etc/nginx/sites-available/project

Begin by specifying that this block should be listening to port 80 and should respond to the server’s IP address.

首先指定此块应侦听端口80,并应响应服务器的IP地址。

server {
    listen 80;
    server_name server_domain_or_IP;
}

Next, we shall instruct Nginx to ignore any issues with locating the favicon. Additionally, we will tell it where to locate static assets collected in ~/project/static directory

接下来,我们将指示Nginx忽略定位收藏夹的任何问题。 此外,我们将告诉它在哪里可以找到~/project/static目录中收集的静态资产

location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/james/project;
    }

Lastly, we will create a block location / { } which will match the rest of the requests.
Within this location, we shall define proxy_params file and later direct traffic to the socket created by the Gunicorn process

最后,我们将创建一个与其他请求匹配的块位置/ { }
在此位置,我们将定义proxy_params文件,然后将流量定向到Gunicorn进程创建的套接字

location / {
        include proxy_params;
        proxy_pass https://unix:/home/james/project/project.sock;
    }

The final configuration file should look something like this

最终配置文件应如下所示

Save and Exit the configuration file

保存并退出配置文件

Let’s Enable the file by linking it to the sites-enabled directory

通过将文件链接到启用站点的目录来启用文件

$ sudo ln -s /etc/nginx/sites-available/project /etc/nginx/sites-enabled

Next, let us test our configuration for any errors

接下来,让我们测试配置是否存在任何错误

$ sudo nginx -t

If all went well, the output should be as shown below

如果一切顺利,输出应如下所示

After testing the Nginx configuration

测试Nginx配置后

$ sudo systemctl restart nginx

Now that we no longer need access to the development server on port 8000, let us remove the rule on the firewall.

现在,我们不再需要访问端口8000上的开发服务器,让我们删除防火墙上的规则。

$ sudo ufw delete allow 8000

Let us also allow port 80

让我们也允许端口80

$ sudo ufw allow 'Nginx Full'

You should now be able to go to your server’s domain or IP address to view your application without specifying port 8000

现在,您无需指定端口8000即可访问服务器的域或IP地址以查看您的应用程序

麻烦提示 (Troubling tips)

1.服务器显示默认的Nginx页面 (1.Server displaying default Nginx page)

If Nginx displays the default page instead of proxying to the Django application, you need to check the /etc/nginx/sites-available/project file and ensure your server’s IP or domain name is correctly indicated. The default page implies that Nginx wasn’t able to match your request and instead was falling back on /etc/nginx/sites-available/default

如果Nginx显示默认页面而不是代理Django应用程序,则需要检查/etc/nginx/sites-available/project文件,并确保正确指示服务器的IP或域名。 默认页面表示Nginx无法匹配您的请求,而是回退到/etc/nginx/sites-available/default

2. 502错误的网关错误而不是Django应用程序 (2. 502 Bad gateway error instead of Django application)

A 502 error is an indication that Nginx web server was not able to successfully proxy the request. To accurately troubleshoot the problem, check out the logs in the error log file as shown and this could give you a clue as to what could be wrong.

502错误表示Nginx Web服务器无法成功代理请求。 为了准确地解决问题,请检查所示错误日志文件中的日志,这可以为您提供有关可能出问题的线索。

$  sudo tail -F /var/log/nginx/error.log

3.“无法连接到服务器”连接被拒绝 (3. “Could not connect to server” Connection refused)

An error you may come across when trying to access some certain components in your web browser is

尝试访问Web浏览器中的某些特定组件时可能遇到的错误是

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 shows that the Django application is unable to connect to the Postgres database
Ensure that Postgres is running by executing

这表明Django应用程序无法连接到Postgres数据库
通过执行以下命令确保Postgres正在运行

$ sudo systemctl status postgresql

If it’s not running, start it and enable it to start on boot

如果它没有运行,请启动它并使它能够在启动时启动

$ sudo systemctl start postgresql
$ sudo systemctl enable postgresql

If you are still having issues, ensure that database settings in
~/myproject/myproject/settings.py are correct.

如果仍然有问题,请确保
~/myproject/myproject/settings.py是正确的。

For further troubleshooting, examine the following logs

有关进一步的故障排除,请检查以下日志

Nginx process logs                 sudo journalctl -u nginx

Nginx access logs                    sudo tail -f  /var/log/nginx/access.log

Nginx error logs	          sudo less /var/log/nginx/error.log


Gunicorn Application logs     sudo journalctl -u gunicorn

As you make changes to the configuration files, ensure that you restart them for the changes to take effect.

更改配置文件时,请确保重新启动它们以使更改生效。

If you decide to make changes to the gunicorn systemd service file, make sure you reload the daemon and restart gunicorn

如果决定更改gunicorn systemd服务文件,请确保重新加载守护程序并重新启动gunicorn

$ sudo systemctl daemon-reload
$ sudo systemctl restart gunicorn

When you make changes to the Nginx server block configuration test the config

当您更改Nginx服务器块配置时,请测试配置

$ sudo nginx -t && sudo systemctl restart nginx

结论 (Conclusion)

Thank you for taking the time in this article. In this article, we set up a Django project in a virtual environment and set up Gunicorn to translate client requests and Nginx to proxy traffic to our Django application.

感谢您抽出宝贵的时间在本文中。 在本文中,我们在虚拟环境中设置了Django项目,并设置了Gunicorn来转换客户端请求,并设置Nginx来将流量代理到我们的Django应用程序。

翻译自: https://www.journaldev.com/28002/django-postgres-nginx-gunicorn-ubuntu

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值