”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何:使用 Docker 将 Django 和 Postgres 应用程序容器化

如何:使用 Docker 将 Django 和 Postgres 应用程序容器化

发布于2024-11-04
浏览:122

This article was originally published on the Shipyard Blog.


As you’re building out your Django and PostgreSQL app, you’re probably thinking about a few boxes you’d like it to check:

  • Portable: can I distribute this between machines or team members?
  • Scalable: is this app able to handle an increase in number of users, requests, or general workload?
  • Cloud native: can I host this app in development, ephemeral, staging, and/or production cloud environments?

Using Docker and Docker Compose can help get your app ready for every stage of the development life cycle, from local to production. In this post, we’ll be covering some of the basics for customizing a Dockerfile and Compose file for a Django app with a Postgres database.

TLDR: Shipyard maintains a Django / Postgres starter application, set up to build and run with Docker and Docker Compose. Fork it here. You can use it as a project template or as a reference for your existing app.

What is Django?

Django is an open source Python-based web framework. It’s primarily used as a backend for web apps. Django follows the “batteries included” philosophy — it comes complete with routing support, a login framework, a web server, database tools, and much more. Django is often compared to Flask, and scores more favorably on almost all fronts.

You’re using Django apps every day. Spotify, Doordash, Instagram, Eventbrite, and Pinterest all have Django in their stacks — which speaks volumes to how extensible and scalable it can be.

Benefits of Dockerizing a Django App

Running a Django app with Docker containers unlocks several new use cases. Right off the bat, it’s an improvement to your local development workflows — making setup cleaner and more straightforward.

If you want to cloud-host your project, you’ll typically need it containerized. The great thing about Docker containers is that they can be used throughout every stage of development, from local to production. You can also distribute your Docker image so others can run it instantly without any installation or building.

At the very least, if you’re including a Dockerfile with your project, you can ensure it builds and runs identically every single time, on every system.

Choosing a Python package manager

Our Python app needs a package manager to track, version, and install its dependencies. This helps us manage dependency inits/updates, instead of executing them individually, and preserve package versions across machines.

Both Pip and Poetry are popular dependency managers for Python, although there are quite a few others circulating around (e.g. uv, Conda, Rye).

Pip is incredibly straightforward. Users can list their packages in a requirements.txt file with their respective versions, and run pip install to set them up. Users can capture existing dependencies and their versions by running pip freeze > requirements.txt in a project’s root.

Poetry a highly-capable package manager for apps of any scale, but it’s slightly less straightforward to configure than Pip (it uses a TOML file with tables, metadata, and scripts). Poetry also uses a lockfile (poetry.lock) to “lock” dependencies at their current versions (and their dependencies by version). This way, if your project works at a certain point in time on a particular machine, this state will be preserved. Running poetry init prompts users with a series of options to generate a pyproject.toml file.

Writing a Dockerfile for a Django app

To Dockerize your Django app, you'll follow the classic Dockerfile structure (set the base image, set the working directory, etc.) and then modify it with the project-specific installation instructions, likely found in the README.

Selecting a base image

We can choose a lightweight Python image to act as our base for this Dockerfile. To browse versions by tag, check out the Python page on Docker Hub. I chose Alpine here since it’ll keep our image small:

FROM python:3.8.8-alpine3.13

Setting a working directory

Here, we will define the working directory within the Docker container. All paths mentioned after will be relative to this.

WORKDIR /srv

Installing system dependencies

There are a few libraries we need to add before we can get Poetry configured:

RUN apk add --update --no-cache \
  gcc \
  libc-dev \
  libffi-dev \
  openssl-dev \
  bash \
  git \
  libtool \
  m4 \
  g   \
  autoconf \
  automake \
  build-base \
  postgresql-dev

Installing Poetry

Next, we’ll ensure we’re using the latest version of Pip, and then use that to install Poetry inside our container:

RUN pip install --upgrade pip
RUN pip install poetry

Installing our project’s dependencies

This app’s dependencies are defined in our pyproject.toml and poetry.lock files. Let’s bring them over to the container’s working directory, and then install from their declarations:

ADD pyproject.toml poetry.lock ./
RUN poetry install

Adding and installing the project itself

Now, we’ll copy over the rest of the project, and install the Django project itself within the container:

ADD src ./src
RUN poetry install

Executing the start command

Finally, we’ll run our project’s start command. In this particular app, it’ll be the command that uses Poetry to start the Django development server:

CMD ["poetry", "run", "python", "src/manage.py", "runserver", "0:8080"]

The complete Dockerfile

When we combine the snippets from above, we’ll get this Dockerfile:

FROM python:3.8.8-alpine3.13

WORKDIR /srv

RUN apk add --update --no-cache \
  gcc \
  libc-dev \
  libffi-dev \
  openssl-dev \
  bash \
  git \
  libtool \
  m4 \
  g   \
  autoconf \
  automake \
  build-base \
  postgresql-dev

RUN pip install --upgrade pip
RUN pip install poetry

ADD pyproject.toml poetry.lock ./
RUN poetry install

ADD src ./src
RUN poetry install

CMD ["poetry", "run", "python", "src/manage.py", "runserver", "0:8080"]

Writing a Docker Compose service definition for Django

We’re going to split this app into two services: django and postgres. Our django service will be built from our Dockerfile, containing all of our app’s local files.

Setting the build context

For this app, we want to build the django service from our single Dockerfile and use the entire root directory as our build context path. We can set our build label accordingly:

django:
  build: .

Setting host and container ports

We can map port 8080 on our host machine to 8080 within the container. This will also be the port we use to access our Django app — which will soon be live at http://localhost:8080.

ports:
  - '8080:8080'

Adding a service dependency

Since our Django app is connecting to a database, we want to instruct Compose to spin up our database container (postgres) first. We’ll use the depends_on label to make sure that service is ready and running before our django service starts:

depends_on:
  - postgres

Creating a bind mount

Since we’ll be sharing files between our host and this container, we can define a bind mount by using the volumes label. To set the volume, we’ll provide a local path, followed by a colon, followed by a path within the container. The ro flag gives the container read-only permissions for these files:

volumes:
  - './src:/srv/src:ro'

The end result

Combining all the options/configurations from above, our django service should look like this:

django:
  build: .
  ports:
    - '8080:8080'
  depends_on:
    - postgres
  volumes:
    - './src:/srv/src:ro'

Adding a PostgreSQL database

Our Django app is configured to connect to a PostgreSQL database. This is defined in our settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'app',
        'USER': 'obscure-user',
        'PASSWORD': 'obscure-password',
        'HOST': 'postgres',
        'PORT': 5432,
    }
}

Pulling the Postgres image

We can migrate our existing database to its own Docker container to isolate it from the base Django app. First, let’s define a postgres service in our Compose file and pull the latest lightweight Postgres image from Docker Hub:

postgres:
  image: 'postgres:14.13-alpine3.20'

Passing in env vars

To configure our PostgreSQL database, we can pass in a few environment variables to set credentials and paths. You may want to consider using a Secrets Manager for this.

environment:
  - POSTGRES_DB=app
  - POSTGRES_USER=obscure-user
  - POSTGRES_PASSWORD=obscure-password
  - PGDATA=/var/lib/postgresql/data/pgdata

Setting host and container ports

We can expose our container port by setting it to the default Postgres port: 5432. For this service, we’re only specifying a single port, which means that the host port will be randomized. This avoids collisions if you’re running multiple Postgres instances.

ports:
  - '5432'

Adding a named data volume

In our postgres definition, we can add a named volume. This is different from the bind mount that we created for the django service. This will persist our data after the Postgres container spins down.

volumes:
  - 'postgres:/var/lib/postgresql/data'

Outside of the service definitions and at the bottom of the Compose file, we’ll declare the named postgres volume again. By doing so, we can reference it from our other services if needed.

volumes:
  postgres:

Putting it all together

And here’s the resulting PostgreSQL definition in our Compose file:

  postgres:
    image: 'postgres:14.13-alpine3.20'
    environment:
      - POSTGRES_DB=app
      - POSTGRES_USER=obscure-user
      - POSTGRES_PASSWORD=obscure-password
      - PGDATA=/var/lib/postgresql/data/pgdata
    ports:
      - '5432'
    volumes:
      - 'postgres:/var/lib/postgresql/data'

volumes:
  postgres:

Deploying our app in a Shipyard ephemeral environment

We can get our app production-ready by deploying it in a Shipyard application — this means we’ll get an ephemeral environment for our base branch, as well as environments for every PR we open.

How To: Containerize a Django and Postgres App with Docker

Adding Docker Compose labels

Shipyard transpiles Compose files to Kubernetes manifests, so we’ll add some labels to make it Kubernetes-compatible.

Under our django service, we can add two custom Shipyard labels:

labels:
  shipyard.init: 'poetry run python src/manage.py migrate'
  shipyard.route: '/'
  1. The shipyard.init label will run a database migration before our django service starts
  2. The shipyard.route label will send HTTP requests to this service’s port

Creating a Shipyard app

Next, you can go to your Shipyard dashboard. If you haven’t already, sign up for a 30-day free trial.

Click the Application button, then select your repo, services, and import your env vars.

How To: Containerize a Django and Postgres App with Docker

Visiting the app

Once it finishes building, you can click the green Visit button to access your short-lived ephemeral environment. What comes next?

  • View your app’s build, deploy, and run logs
  • Use our GitHub Action or CircleCI orb to integrate with your CI/CD
  • Add SSO visitors to your app
  • Create a PR to see your code changes in a new environment

And that’s all!

Now you have a fully containerized Django app with a database! You can run it locally with Docker Compose, preview and test it in an ephemeral environment, and iterate until it’s production-ready.

Want to Dockerize a Yarn app next? Check out our guide!

版本声明 本文转载于:https://dev.to/shipyard/how-to-containerize-a-django-and-postgres-app-with-docker-1kb7?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-11-17
  • 如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 识别今天生日的用户使用 MySQL 确定今天是否是用户的生日涉及查找生日匹配的所有行今天的日期。这可以通过一个简单的 MySQL 查询来实现,该查询将存储为 UNIX 时间戳的生日与今天的日期进行比较。以下 SQL 查询将获取今天有生日的所有用户: FROM USERS ...
    编程 发布于2024-11-17
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-11-17
  • 为什么我的 PDO 更新查询无法修改 MySQL 中的特定行?
    为什么我的 PDO 更新查询无法修改 MySQL 中的特定行?
    使用 PDO 进行 MySQL 更新查询当尝试使用 PDO 和 MySQL 更新数据库行时,您可能会遇到这样的情况:您的代码执行失败。本指南探讨了此错误的可能原因并提供了解决方案。错误:不正确的 UPDATE 语法您遇到的错误源于不正确的 UPDATE 语法。具体来说,您的查询正在尝试用提供的值替换...
    编程 发布于2024-11-17
  • 数据库迁移对于 Golang 服务,为什么重要?
    数据库迁移对于 Golang 服务,为什么重要?
    DB Migration, why it matters? Have you ever faced the situations when you deploy new update on production with updated database schemas, but ...
    编程 发布于2024-11-17
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-11-17
  • 为什么在 Java 中连接空字符串不会抛出 NullPointerException?
    为什么在 Java 中连接空字符串不会抛出 NullPointerException?
    Java 中连接空字符串在 Java 中,连接空字符串可能看起来违反直觉,会导致出现 NullPointerException。但是,此操作成功执行,结果是一个包含“null”的字符串,后跟连接的字符串。为什么会这样?根据 Java 语言规范(JLS) 8,§ 15.18.1,在字符串连接期间,空引...
    编程 发布于2024-11-17
  • Java 正则表达式中的捕获组如何工作?
    Java 正则表达式中的捕获组如何工作?
    了解 Java 正则表达式捕获组在此代码片段中,我们使用 Java 的正则表达式 (regex) 库来提取字符串的一部分。正则表达式定义为“(.)(\d )(.)”,其中:(.*):匹配下一组之前的任意数量的任意字符.(\d ): 匹配前一组之后的任意数量的数字。(.*): 匹配前一组之后的任意数量...
    编程 发布于2024-11-17
  • 如何在 JavaScript 中将提示框中的用户输入转换为数值?
    如何在 JavaScript 中将提示框中的用户输入转换为数值?
    从提示框中检索数字输入将用户输入从提示框转换为数值对于在 JavaScript 中执行数学计算至关重要。这种转换可以通过函数 parseInt() 和 parseFloat() 来实现。parseInt() 和 parseFloat()parseInt() 和 parseFloat() 将数字的字符...
    编程 发布于2024-11-17
  • 如何将 C++ 代码转换为 C:自动和手动方法指南
    如何将 C++ 代码转换为 C:自动和手动方法指南
    将 C 代码转换为 C考虑到语言之间的复杂性和差异,将 C 代码转换为纯 C 可能是一项艰巨的任务。然而,有自动化工具和手动方法来应对这一挑战。自动转换工具值得考虑的一个自动化解决方案是 Comeau 的 C 编译器。该工具从 C 生成 C 代码,允许您维护 C 代码并根据需要将其转换为 C。但是,...
    编程 发布于2024-11-17
  • 在 PHP 中调整 PNG 大小时如何保持透明度?
    在 PHP 中调整 PNG 大小时如何保持透明度?
    在 PHP 中调整 PNG 大小时保留透明度在 PHP 中调整具有透明背景的 PNG 图像大小时,确保透明度是至关重要的维持。但网上很多代码示例都未能很好地实现这一点,导致调整大小后背景变成黑色。要解决这个问题,需要对代码进行具体调整。在执行 imagecolorallocatealpha() 函数...
    编程 发布于2024-11-17
  • 除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    无需强制转换即可上下文转换为 bool您的类定义了对 bool 的显式转换,使您能够在条件语句中直接使用其实例“t”。然而,这种显式转换提出了一个问题:“t”在哪里可以在不进行强制转换的情况下用作 bool?上下文转换场景C 标准指定了四种值可以根据上下文转换为 bool 的主要场景:语句:if、w...
    编程 发布于2024-11-17
  • 如何在 Internet Explorer 10 中应用灰度滤镜?
    如何在 Internet Explorer 10 中应用灰度滤镜?
    在 Internet Explorer 10 中应用灰度筛选器Internet Explorer 10 对使用传统 CSS 方法应用灰度筛选器提出了挑战。与以前版本的 IE 不同,不再支持 DX 滤镜和前缀灰度滤镜。解决方案:SVG Overlay要在 IE10 中对灰度图像进行处理,您可以使用 S...
    编程 发布于2024-11-17
  • Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta:列偏移的删除和恢复Bootstrap 4 在其 Beta 1 版本中引入了重大更改柱子偏移了。然而,随着 Beta 2 的后续发布,这些变化已经逆转。从 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    编程 发布于2024-11-17
  • 开源软件项目的免费人工智能代码审查
    开源软件项目的免费人工智能代码审查
    如果您参与开源软件,您就会知道代码审查的重要性。它们不仅仅是捕捉错误,还确保代码质量、安全性和可维护性,帮助每个贡献者无缝协作。但让我们面对现实吧,代码审查非常耗时。手动审查每个拉取请求 (PR) 可能会减慢开发速度,尤其是在资源有限的开源项目中。 Bito 的人工智能代码审查代理——一种自动化工具...
    编程 发布于2024-11-17

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3