Make your life easy with Docker Compose

Saad Ali
2 min readAug 14, 2022

--

This article is a continuation of our previous article where we are containerizing our Django App. In this short article, we will do the same thing that is already done in the previous article but this time with Docker Compose. If you haven't read the first part, you can check it out here

Docker Compose is a powerful tool that helps us dockerizing our application in just a few steps we don't need to create a network, create separate apps then connect them. All can be done just with a single command. Cool?

Docker Compose works with another file docker-compose.yml. Let's create it in the same directory and paste the below code

version: "3.9"

services:
db:
image: postgres:14-alpine
volumes:
- postgresql-data:/var/lib/postgresql/data
ports:
- "5431:5432"
environment:
- POSTGRES_DB=mydb
- POSTGRES_USER=root
- POSTGRES_PASSWORD=root

app:
build:
context: .
dockerfile: Dockerfile
command: bash -c "python manage.py runserver 0.0.0.0:8000"
ports:
- "8000:8000"
volumes:
- ./:/code
environment:
- POSTGRES_NAME=mydb
- POSTGRES_USER=root
- POSTGRES_PASSWORD=root
depends_on:
- db
volumes:
postgresql-data:
driver: local

We have two services db and app Let's break it down

db:

  • postgres:14-alpine: base image
  • ports: endpoints on which our DB container is accessible outside the network
  • volumes: to persist data, either generated by or used by docker container
  • environment: DB credentials

app:

  • build: we are not using a base image for our app, using it is already defined in Dockerfile. So, we just need to build our Dockerfile (. tells docker to search Dockerfile in the current directory)
  • ports: endpoints on which our app container is accessible outside the network
  • volumes: to persist data, either generated by or used by docker container
  • environment: DB credentials
  • depends_on: our service app depends on db app, so we need to mention that

Now we don't need to mention the CMD command in Dockerfile as docker-compose already contains it

FROM python:3.9-buster
WORKDIR /code
COPY . /code
RUN pip install -r requirements.txt

That’s it! We don't need to create a network or database container separately, Docker Compose will create a database container inside a network for us by just reading the docker-compose.yml file

Let's run

Docker-compose up --build

Now to check your running containers run

Docker ps

Hope you like this article. Feel free to share your suggestions/feedback in the comment section

--

--

Saad Ali
Saad Ali

Written by Saad Ali

Software Engineer. Love to work in Python, Django and Rails

No responses yet