如何使用Docker构建Django和Gunicorn应用程序

介绍 (Introduction)

Django is a powerful web framework that can help you get your Python application off the ground quickly. It includes several convenient features like an object-relational mapper, user authentication, and a customizable administrative interface for your application. It also includes a caching framework and encourages clean app design through its URL Dispatcher and Template system.

Django是一个功能强大的网络框架,可以帮助您快速启动Python应用程序。 它包括几个方便的功能,例如对象关系映射器 ,用户身份验证和适用于您的应用程序的可自定义管理界面。 它还包括一个缓存框架,并通过其URL DispatcherTemplate系统鼓励进行干净的应用程序设计。

In this tutorial, you’ll learn how to build a scalable and portable Django Polls app with Docker containers. Out of the box, a Django app requires several modifications to run effectively inside of containers, like logging to standard output streams and configuring itself through environment variables passed into the container. In addition, offloading static assets like JavaScript and CSS stylesheets to object storage allows you to streamline and centralize the management of these files in a multi-container environment.

在本教程中,您将学习如何使用Docker容器构建可扩展且可移植的Django Polls应用程序。 Django应用程序开箱即用,需要进行一些修改才能在容器内有效运行,例如登录到标准输出流并通过传递到容器中的环境变量对其进行配置。 此外,将JavaScript和CSS样式表之类的静态资产卸载到对象存储中,可以使您在多容器环境中简化和集中管理这些文件。

You’ll implement these modifications—inspired by the Twelve-Factor methodology for building scalable, cloud-native web apps—on a sample Django Polls app. Then, you’ll build the application image and run the containerized app with Docker.

您将在示例Django Polls应用程序上实施这些修改(受十二要素方法启发,用于构建可扩展的云原生Web应用程序)。 然后,您将构建应用程序映像并使用Docker运行容器化的应用程序。

By the end of this tutorial, you’ll have containerized the setup in How to Set Up a Scalable Django App. In subsequent tutorials in this series, you’ll learn how to use Docker Compose to pair the Django container with an Nginx reverse proxy, and deploy this architecture to a Kubernetes cluster.

在本教程结束时,您将在如何设置可扩展Django应用程序中将设置容器化。 在本系列的后续教程中,您将学习如何使用Docker Compose将Django容器与Nginx反向代理配对,并将此架构部署到Kubernetes集群。

It’s highly recommended to work through the tutorial to understand the changes you’re making to the app, but if you’d like to skip ahead, you can obtain the modified code from the polls-docker branch of the Polls app GitHub repository.

强烈建议您通读本教程,以了解对应用程序所做的更改,但是如果您想跳过,可以从Polls应用程序GitHub存储库的polls-docker分支中获取修改后的代码。

先决条件 (Prerequisites)

To follow this tutorial, you’ll need:

要遵循本教程,您需要:

第1步-创建PostgreSQL数据库和用户 (Step 1 — Creating the PostgreSQL Database and User)

To begin, we’ll connect to the PostgreSQL server from the Ubuntu instance. Then, we’ll create a PostgreSQL database and user for the Django app, and configure the database to work effectively with Django.

首先,我们将从Ubuntu实例连接到PostgreSQL服务器。 然后,我们将为Django应用程序创建一个PostgreSQL数据库和用户,并配置该数据库以使其与Django有效配合使用。

Before we connect to the database from our Ubuntu machine (not the app container), we need to install the postgresql-client package from the Ubuntu repositories. First update the local apt package index and then download and install the package:

在从Ubuntu机器(不是应用程序容器)连接到数据库之前,我们需要从Ubuntu存储库中安装postgresql-client软件包。 首先更新本地apt软件包索引,然后下载并安装该软件包:

sudo apt update
sudo apt install postgresql-client

Hit Y and then ENTER when prompted to begin downloading and installing the packages.

当提示您开始下载和安装软件包时,请按Y ,然后按ENTER

Now that you’ve installed the client, we’ll use it to create a database and database user for our Django application.

现在您已经安装了客户端,我们将使用它为Django应用程序创建数据库和数据库用户。

To begin, grab the Connection Parameters for your cluster by navigating to Databases from the Cloud Control Panel, and clicking into your database. You should see a Connection Details box containing some Connection parameters for your cluster. Note these down.

首先,通过从Cloud Control Panel导航到Databases ,然后单击进入数据库,获取集群的Connection Parameters 。 您应该看到一个Connection Details框,其中包含群集的一些Connection参数 。 注意这些。

Back on the command line, log in to your cluster using these credentials and the psql PostgreSQL client we just installed:

返回命令行,使用以下凭据和我们刚安装的psql PostgreSQL客户端登录到集群:

psql -U username -h host -p port -d database --set=sslmode=require

When prompted, enter the password displayed alongside the Postgres username, and hit ENTER.

出现提示时,输入显示在Postgres用户名旁边的密码,然后按ENTER

You will be given a PostgreSQL prompt from which you can manage the database.

系统将显示一个PostgreSQL提示,您可以从中管理数据库。

First, create a database for your project called polls:

首先,为您的项目创建一个名为polls的数据库:

CREATE DATABASE polls;

Note: Every Postgres statement must end with a semicolon, so make sure that your command ends with one if you are experiencing issues.

注意:每个Postgres语句必须以分号结尾,因此,如果遇到问题,请确保命令以1结尾。

We can now switch to the polls database:

现在,我们可以切换到polls数据库:

\c polls;

Next, create a database user for the project. Make sure to select a secure password:

接下来,为项目创建一个数据库用户。 确保选择一个安全密码:

CREATE USER sammy WITH PASSWORD 'password';

We’ll now 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项目本身的建议。

Enter the following commands at the PostgreSQL prompt:

在PostgreSQL提示符下输入以下命令:

ALTER ROLE sammy SET client_encoding TO 'utf8';
ALTER ROLE sammy SET default_transaction_isolation TO 'read committed';
ALTER ROLE sammy SET timezone TO 'UTC';

Now we can give our new user access to administer our new database:

现在,我们可以授予新用户访问权限来管理新数据库:

GRANT ALL PRIVILEGES ON DATABASE polls TO sammy;

When you are finished, exit out of the PostgreSQL prompt by typing:

完成后,通过键入以下命令退出PostgreSQL提示符:

\q

A Django app, properly configured, can now connect to and manage this database. In the next step, we’ll clone the Polls app code from GitHub and explicitly define its Python package dependencies.

正确配置的Django应用现在可以连接并管理该数据库。 在下一步中,我们将从GitHub克隆Polls应用程序代码,并显式定义其Python包依赖关系。

第2步-克隆应用程序存储库并声明依赖关系 (Step 2 — Cloning App Repository and Declaring Dependencies)

To begin the process of containerizing our Django Polls app, we’ll first clone the django-polls repository, which contains the complete code for the Django project’s tutorial Polls app.

要开始对Django Polls应用程序进行容器化的过程,我们将首先克隆django-polls存储库,其中包含Django项目的教程 Polls应用程序的完整代码。

Log in to your server, create a directory called polls-project and use git to clone the django-polls repo from GitHub:

登录到您的服务器,创建一个名为polls-project的目录,并使用git从GitHub复制django-polls库:

mkdir polls-project
cd polls-project
git clone https://github.com/do-community/django-polls.git

Access the django-polls directory and list the repository contents:

访问django-polls目录并列出存储库内容:

cd django-polls
ls

   
   
   
Output
LICENSE README.md manage.py mysite polls templates

You should see the following objects:

您应该看到以下对象:

  • manage.py: The main command-line utility used to manipulate the app.

    manage.py :用于操作应用程序的主要命令行实用程序。

  • polls: Contains the polls app code.

    polls :包含polls应用程序代码。

  • mysite: Contains Django project-scope code and settings.

    mysite :包含Django项目范围的代码和设置。

  • templates: Contains custom template files for the administrative interface.

    templates :包含管理界面的定制模板文件。

To learn more about the project structure and files, consult Creating a Project from the official Django documentation.

要了解有关项目结构和文件的更多信息,请参考官方Django文档中的创建项目

In this directory we’ll also create a file called requirements.txt that will contain the Django app’s Python dependencies.

在此目录中,我们还将创建一个名为requirements.txt的文件,其中将包含Django应用程序的Python依赖项。

Open a file called requirements.txt in your editor of choice and paste in the following Python dependencies:

在您选择的编辑器中打开一个名为requirements.txt的文件,并粘贴以下Python依赖项:

polls-project/django-polls/requirements.txt
polls-project / django-polls / requirements.txt
boto3==1.9.252
botocore==1.12.252
Django==2.2.6
django-storages==1.7.2
docutils==0.15.2
gunicorn==19.9.0
jmespath==0.9.4
psycopg2==2.8.3
python-dateutil==2.8.0
pytz==2019.3
s3transfer==0.2.1
six==1.12.0
sqlparse==0.3.0
urllib3==1.25.6

Here we install Django, the django-storages plugin for offloading static assets to object storage, the gunicorn WSGI server, the psycopg2 PostgreSQL adapter, as well as some additional dependency packages. Note that we explicitly list and version every Python package required by our app.

在这里,我们安装Django,用于将静态资产卸载到对象存储的django-storages gunicorn插件, gunicorn WSGI服务器, psycopg2 PostgreSQL适配器以及一些其他依赖包。 请注意,我们明确列出了应用所需的每个Python

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值