찾다
백엔드 개발파이썬 튜토리얼방법: Docker를 사용하여 Django 및 Postgres 앱 컨테이너화

本文原發表於船廠部落格。


當您建立 Django 和 PostgreSQL 應用程式時,您可能正在考慮希望它檢查的幾個框:

  • 便攜式:我可以在機器或團隊成員之間分發它嗎?
  • 可擴充:此應用程式能夠處理使用者數量、請求或一般工作負載的增加嗎?
  • 雲端原生:我可以在開發、臨時、暫存和/或生產雲端環境中託管此應用程式嗎?

使用 Docker 和 Docker Compose 可以幫助您的應用程式為開發生命週期的每個階段(從本地到生產)做好準備。在這篇文章中,我們將介紹使用 Postgres 資料庫為 Django 應用程式自訂 Dockerfile 和 Compose 檔案的一些基礎知識。

TLDR: Shipyard 維護一個 Django / Postgres 入門應用程序,設定為使用 Docker 和 Docker Compose 建置和運行。在這裡分叉。您可以將其用作專案範本或作為現有應用程式的參考。

姜戈是什麼?

Django 是一個基於 Python 的開源 Web 框架。它主要用作網路應用程式的後端。 Django 遵循「自備電池」的理念——它配備了路由支援、登入框架、Web 伺服器、資料庫工具等等。 Django 經常被拿來與 Flask 進行比較,幾乎在所有方面都得分更高。

您每天都在使用 Django 應用程式。 Spotify、Doordash、Instagram、Eventbrite 和 Pinterest 都擁有 Django - 這充分說明了它的可擴展性和可擴展性。

Docker 化 Django 應用程式的好處

使用 Docker 容器運行 Django 應用程式可以解鎖多個新用例。它立即改進了您的本地開發工作流程 - 使設定更清晰、更簡單。

如果您想在雲端託管您的項目,通常需要將其容器化。 Docker 容器的優點在於它們可以在從本地到生產的每個開發階段使用。您也可以分發您的 Docker 映像,以便其他人可以立即運行它,而無需任何安裝或建置。

至少,如果您在專案中包含 Dockerfile,則可以確保它每次在每個系統上都以相同的方式建置和運行。

選擇 Python 套件管理器

我們的 Python 應用程式需要一個套件管理器來追蹤、版本控制和安裝其依賴項。這有助於我們管理依賴項初始化/更新,而不是單獨執行它們,並跨機器保留套件版本。

Pip 和 Poetry 都是 Python 流行的依賴管理器,儘管還有很多其他的依賴管理器(例如 uv、Conda、Rye)。

Pip 非常簡單。使用者可以在requirements.txt檔案中列出他們的軟體包及其各自的版本,然後執行pip install來設定它們。使用者可以透過執行 pip freeze > 來捕獲現有的依賴項及其版本。專案根目錄中的requirements.txt。

Poetry 是適用於任何規模的應用程式的高效能套件管理器,但它的配置比 Pip 稍微簡單一些(它使用帶有表、元資料和腳本的 TOML 檔案)。 Poetry 也使用鎖定檔案 (poetry.lock) 來「鎖定」目前版本的依賴項(以及按版本依賴項)。這樣,如果您的專案在特定時間點在特定機器上運行,則該狀態將被保留。運行詩歌 init 會提示使用者一系列選項來產生 pyproject.toml 檔案。

為 Django 應用程式編寫 Dockerfile

要 Dockerize 您的 Django 應用程序,您將遵循經典的 Dockerfile 結構(設定基本映像、設定工作目錄等),然後使用特定於專案的安裝說明(可能在自述文件中找到)對其進行修改。

選擇基礎影像

我們可以選擇一個輕量級的 Python 映像作為這個 Dockerfile 的基礎。若要按標籤瀏覽版本,請查看 Docker Hub 上的 Python 頁面。我在這裡選擇 Alpine,因為它會使我們的圖像保持較小:

FROM python:3.8.8-alpine3.13

設定工作目錄

在這裡,我們將定義 Docker 容器內的工作目錄。後面提到的所有路徑都與此相關。

WORKDIR /srv

安裝系統依賴項

在設定 Poetry 之前,我們需要加入一些函式庫:

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

安裝詩歌

接下來,我們將確保使用最新版本的 Pip,然後使用它在我們的容器內安裝 Poetry:

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!

위 내용은 방법: Docker를 사용하여 Django 및 Postgres 앱 컨테이너화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Python vs. C : 학습 곡선 및 사용 편의성Python vs. C : 학습 곡선 및 사용 편의성Apr 19, 2025 am 12:20 AM

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

Python vs. C : 메모리 관리 및 제어Python vs. C : 메모리 관리 및 제어Apr 19, 2025 am 12:17 AM

Python과 C는 메모리 관리 및 제어에 상당한 차이가 있습니다. 1. Python은 참조 계산 및 쓰레기 수집을 기반으로 자동 메모리 관리를 사용하여 프로그래머의 작업을 단순화합니다. 2.C는 메모리 수동 관리가 필요하므로 더 많은 제어를 제공하지만 복잡성과 오류 위험을 증가시킵니다. 선택할 언어는 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.

과학 컴퓨팅을위한 파이썬 : 상세한 모양과학 컴퓨팅을위한 파이썬 : 상세한 모양Apr 19, 2025 am 12:15 AM

과학 컴퓨팅에서 Python의 응용 프로그램에는 데이터 분석, 머신 러닝, 수치 시뮬레이션 및 시각화가 포함됩니다. 1.numpy는 효율적인 다차원 배열 및 수학적 함수를 제공합니다. 2. Scipy는 Numpy 기능을 확장하고 최적화 및 선형 대수 도구를 제공합니다. 3. 팬더는 데이터 처리 및 분석에 사용됩니다. 4. matplotlib는 다양한 그래프와 시각적 결과를 생성하는 데 사용됩니다.

파이썬 및 C : 올바른 도구 찾기파이썬 및 C : 올바른 도구 찾기Apr 19, 2025 am 12:04 AM

Python 또는 C를 선택할 것인지 프로젝트 요구 사항에 따라 다릅니다. 1) Python은 간결한 구문 및 풍부한 라이브러리로 인해 빠른 개발, 데이터 과학 및 스크립팅에 적합합니다. 2) C는 컴파일 및 수동 메모리 관리로 인해 시스템 프로그래밍 및 게임 개발과 같은 고성능 및 기본 제어가 필요한 시나리오에 적합합니다.

데이터 과학 및 기계 학습을위한 파이썬데이터 과학 및 기계 학습을위한 파이썬Apr 19, 2025 am 12:02 AM

Python은 데이터 과학 및 기계 학습에 널리 사용되며 주로 단순성과 강력한 라이브러리 생태계에 의존합니다. 1) 팬더는 데이터 처리 및 분석에 사용되며, 2) Numpy는 효율적인 수치 계산을 제공하며 3) Scikit-Learn은 기계 학습 모델 구성 및 최적화에 사용되며 이러한 라이브러리는 Python을 데이터 과학 및 기계 학습에 이상적인 도구로 만듭니다.

Python 학습 : 2 시간의 일일 연구가 충분합니까?Python 학습 : 2 시간의 일일 연구가 충분합니까?Apr 18, 2025 am 12:22 AM

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

웹 개발을위한 파이썬 : 주요 응용 프로그램웹 개발을위한 파이썬 : 주요 응용 프로그램Apr 18, 2025 am 12:20 AM

웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화

Python vs. C : 성능과 효율성 탐색Python vs. C : 성능과 효율성 탐색Apr 18, 2025 am 12:20 AM

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.