」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何:使用 Docker 將 Django 和 Postgres 應用程式容器化

如何:使用 Docker 將 Django 和 Postgres 應用程式容器化

發佈於2024-11-04
瀏覽:298

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]刪除
最新教學 更多>
  • 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
  • 如何使用 jQuery 製作背景顏色動畫?
    如何使用 jQuery 製作背景顏色動畫?
    使用 jQuery 淡化背景顏色引人注目的網站元素通常需要微妙的動畫,例如淡入和淡出。雖然 jQuery 廣泛用於動畫文字內容,但它也可用於動態增強背景顏色。 在 jQuery 中淡入/淡出背景顏色進行操作要使用 jQuery 設定元素的背景顏色,您首先需要合併 jQueryUI 函式庫。整合後,可...
    程式設計 發佈於2024-11-17
  • 開源軟體專案的免費人工智慧程式碼審查
    開源軟體專案的免費人工智慧程式碼審查
    如果您參與開源軟體,您就會知道程式碼審查的重要性。它們不僅僅是捕捉錯誤,還確保程式碼品質、安全性和可維護性,幫助每個貢獻者無縫協作。但讓我們面對現實吧,程式碼審查非常耗時。手動審查每個拉取請求 (PR) 可能會減慢開發速度,尤其是在資源有限的開源專案中。 Bito 的人工智慧程式碼審查代理——一種...
    程式設計 發佈於2024-11-17
  • 是否可以在 PHP 重定向中設定自訂標頭?
    是否可以在 PHP 重定向中設定自訂標頭?
    PHP 重定向中的自訂標頭:不可能的請求使用PHP 重定向到頁面時,您可能會在嘗試通過時遇到挑戰以及帶有重定向的自訂HTTP 標頭。重定向的標準方法涉及使用 header("Location: http://...") 語法。然而,這種方法只為觸發重定向的回應設定標頭,而不是為重...
    程式設計 發佈於2024-11-17
  • 如何用CSS消除影像間距?
    如何用CSS消除影像間距?
    透過 CSS 消除圖像間距在 HTML 中,當連續放置多個圖像時,它們之間會出現一個空格。在某些設計場景中,這可能會造成視覺破壞。雖然有許多解決方法,例如手動換行或 HTML 註釋,但有一個使用 CSS 的優雅解決方案。 要有效刪除圖片之間的空白,請利用以下 CSS 屬性:img { displ...
    程式設計 發佈於2024-11-17
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-11-17
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-17
  • 如何在 Keras 中實現自己的損失函數?
    如何在 Keras 中實現自己的損失函數?
    Keras 中的自訂損失函數實作在 Keras 中,可以實現自訂損失函數來滿足特定的訓練要求。其中一個函數是骰子誤差係數,它測量真實標籤和預測標籤之間的重疊。 要在 Keras 中建立自訂損失函數,請依照下列步驟操作:1。實作係數函數骰子誤差係數可以寫成:dice coefficient = (2 ...
    程式設計 發佈於2024-11-17
  • Go如何在沒有傳統機制的情況下實現多型?
    Go如何在沒有傳統機制的情況下實現多型?
    探討Go語言中的多態性在物件導向程式設計中,多態性允許物件根據其類別表現出不同的行為。但在Go中,多態性的概念並不是傳統意義上的實現。讓我們深入探討一下這背後的原因,探討如何在 Go 中實現類似的功能。 為什麼 Go 缺乏傳統的多態性Go 不是傳統的物件導向語言。它採用了不同的方法,使用:組合:由其...
    程式設計 發佈於2024-11-17
  • 如何在Java中正確透過套接字傳輸檔案?
    如何在Java中正確透過套接字傳輸檔案?
    Java 透過套接字傳輸檔案:傳送和接收位元組數組Java 透過套接字傳輸檔案:傳送和接收位元組數組在Java 中,透過套接字傳輸檔案涉及將檔案轉換為位元組數組,透過套接字發送它們,然後在接收端將位元組轉換回檔案。本文解決了 Java 開發人員在實作此文件傳輸功能時遇到的問題。 伺服器端問題byte...
    程式設計 發佈於2024-11-17
  • 如何在 JavaScript 中格式化數字以顯示最少的小數位數?
    如何在 JavaScript 中格式化數字以顯示最少的小數位數?
    在JavaScript 中格式化數字關於在JavaScript 中格式化數字的查詢,您可以利用內建函數toLocaleString() 和minimumFractionDigits選項。 toLocaleString() 方法可讓您根據使用者的區域設定或指定的區域設定格式化數字。透過將minimum...
    程式設計 發佈於2024-11-17
  • 如何在 Go 中將數字轉換為字母?
    如何在 Go 中將數字轉換為字母?
    在Go 中將數字轉換為字母了解了將數字轉換為字母的需要,讓我們探索在Go 中實現這一目標的各種方法.數字到符文的轉換一種簡單的方法是將數字添加到常量'A' - 1,其中每個數字相加代表字母表中的一個字母。例如,加 1 得到“A”,加 2 得到“B”。 func toChar(i in...
    程式設計 發佈於2024-11-17
  • 如何在 PHP 中提取不含副檔名的檔名?
    如何在 PHP 中提取不含副檔名的檔名?
    在PHP 中提取不帶擴展名的文件名使用神奇常數__FILE__ 可以輕鬆獲取PHP 中當前執行腳本的文件名。但是,如果您需要提取不含副檔名的檔案名,例如“.php”後綴,則過程略有不同。 basename() 解決方案:若要使用basename()函數刪除副檔名,您可以:basename(__FIL...
    程式設計 發佈於2024-11-17
  • 如何在 PHP 和 MySQL 中同步時區?
    如何在 PHP 和 MySQL 中同步時區?
    在PHP 和MySQL 中同步時區您正在開發一個需要使用PHP date() 函數在MySQL 中儲存日期的應用程式。有必要使用 NOW() 在 MySQL 中比較這些日期來計算時間差異。但是,PHP date() 函數使用 PHP 中定義的時區,而 NOW() 使用 MySQL 伺服器中配置的時區...
    程式設計 發佈於2024-11-17
  • 如何使用準備好的語句在 PHP MySQLi 中準備安全更新查詢?
    如何使用準備好的語句在 PHP MySQLi 中準備安全更新查詢?
    如何為更新查詢準備語句為了增強使用PHP MySQLi 查詢更新資料庫時的資料安全性,建議採用準備好的聲明。雖然 PHP 文件提供了有關 bind_param() 的信息,但它缺少特定於更新查詢的範例。 讓我們深入研究如何為更新查詢制定準備好的語句:準備查詢語句:將更新查詢中的所有變數替換為問題標記...
    程式設計 發佈於2024-11-17

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3