Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Cara: Menyimpan Apl Django dan Postgres dengan Docker

Cara: Menyimpan Apl Django dan Postgres dengan Docker

王林
王林asal
2024-09-10 08:30:37424semak imbas

Artikel ini pada asalnya diterbitkan di Blog Shipyard.


Semasa anda membina apl Django dan PostgreSQL anda, anda mungkin memikirkan beberapa kotak yang ingin anda semak:

  • Mudah alih: bolehkah saya mengedarkan ini antara mesin atau ahli pasukan?
  • Boleh skala: adakah apl ini mampu mengendalikan peningkatan dalam bilangan pengguna, permintaan atau beban kerja am?
  • Cloud native: bolehkah saya mengehoskan apl ini dalam pembangunan, sementara, pementasan dan/atau persekitaran awan pengeluaran?

Menggunakan Docker dan Docker Compose boleh membantu menyediakan apl anda untuk setiap peringkat kitaran hayat pembangunan, daripada tempatan kepada pengeluaran. Dalam siaran ini, kami akan membincangkan beberapa asas untuk menyesuaikan fail Dockerfile dan Compose untuk apl Django dengan pangkalan data Postgres.

TLDR: Shipyard mengekalkan aplikasi pemula Django / Postgres, disediakan untuk membina dan menjalankan dengan Docker dan Docker Compose. Garpu di sini. Anda boleh menggunakannya sebagai templat projek atau sebagai rujukan untuk apl sedia ada anda.

Apakah Django?

Django ialah rangka kerja web berasaskan Python sumber terbuka. Ia digunakan terutamanya sebagai bahagian belakang untuk apl web. Django mengikut falsafah "termasuk bateri" — ia dilengkapi dengan sokongan penghalaan, rangka kerja log masuk, pelayan web, alat pangkalan data dan banyak lagi. Django sering dibandingkan dengan Flask dan mendapat markah yang lebih baik pada hampir semua bahagian.

Anda menggunakan apl Django setiap hari. Spotify, Doordash, Instagram, Eventbrite dan Pinterest semuanya mempunyai Django dalam timbunan mereka — yang menggambarkan kelantangan tentang sejauh mana ia boleh dikembangkan dan berskala.

Faedah Melabuhkan Apl Django

Menjalankan apl Django dengan bekas Docker membuka kunci beberapa kes penggunaan baharu. Sejurus selepas itu, ini merupakan peningkatan kepada aliran kerja pembangunan setempat anda — menjadikan persediaan lebih bersih dan lebih mudah.

Jika anda ingin mengehos projek anda dengan awan, anda biasanya memerlukannya dalam bekas. Perkara yang menarik tentang bekas Docker ialah ia boleh digunakan sepanjang setiap peringkat pembangunan, dari tempatan hingga pengeluaran. Anda juga boleh mengedarkan imej Docker anda supaya orang lain boleh menjalankannya serta-merta tanpa sebarang pemasangan atau pembinaan.

Sekurang-kurangnya, jika anda menyertakan Dockerfile dengan projek anda, anda boleh memastikan ia dibina dan berjalan secara sama setiap masa, pada setiap sistem.

Memilih pengurus pakej Python

Apl Python kami memerlukan pengurus pakej untuk menjejak, versi dan memasang kebergantungannya. Ini membantu kami mengurus inits/kemas kini pergantungan, bukannya melaksanakannya secara individu dan mengekalkan versi pakej merentas mesin.

Kedua-dua Pip dan Puisi ialah pengurus pergantungan yang popular untuk Python, walaupun terdapat beberapa orang lain yang beredar di sekitar (cth. uv, Conda, Rye).

Pip adalah sangat mudah. Pengguna boleh menyenaraikan pakej mereka dalam fail requirements.txt dengan versi masing-masing dan menjalankan pemasangan pip untuk menyediakannya. Pengguna boleh menangkap kebergantungan sedia ada dan versinya dengan menjalankan pip freeze > requirements.txt dalam akar projek.

Puisi pengurus pakej berkebolehan tinggi untuk apl dalam sebarang skala, tetapi ia kurang mudah untuk dikonfigurasikan berbanding Pip (ia menggunakan fail TOML dengan jadual, metadata dan skrip). Puisi juga menggunakan fail kunci (poetry.lock) untuk "mengunci" kebergantungan pada versi semasanya (dan kebergantungan mereka mengikut versi). Dengan cara ini, jika projek anda berfungsi pada masa tertentu pada mesin tertentu, keadaan ini akan dikekalkan. Menjalankan puisi init menggesa pengguna dengan satu siri pilihan untuk menjana fail pyproject.toml.

Menulis fail Docker untuk apl Django

Untuk Dockerize apl Django anda, anda akan mengikut struktur Dockerfile klasik (tetapkan imej asas, tetapkan direktori kerja, dsb.) dan kemudian ubah suainya dengan arahan pemasangan khusus projek, mungkin terdapat dalam README.

Memilih imej asas

Kami boleh memilih imej Python yang ringan untuk bertindak sebagai asas kami untuk Dockerfile ini. Untuk menyemak imbas versi mengikut teg, lihat halaman Python di Docker Hub. Saya memilih Alpine di sini kerana ia akan mengekalkan imej kami kecil:

FROM python:3.8.8-alpine3.13

Menetapkan direktori kerja

Di sini, kami akan mentakrifkan direktori kerja dalam bekas Docker. Semua laluan yang disebut selepas ini adalah relatif kepada ini.

WORKDIR /srv

Memasang kebergantungan sistem

Terdapat beberapa perpustakaan yang perlu kami tambahkan sebelum kami boleh mengkonfigurasi Puisi:

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

Memasang Puisi

Seterusnya, kami akan memastikan kami menggunakan versi terkini Pip, dan kemudian menggunakannya untuk memasang Puisi di dalam bekas kami:

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!

Atas ialah kandungan terperinci Cara: Menyimpan Apl Django dan Postgres dengan Docker. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn