Skip to content

Compose

Compose is a Docker utility that allows you to build and run containers in a reproducible manner, based on a configuration file named docker-compose.yml.

Note

docker-compose (hyphenated) is a standalone python tool which is gradually being replaced by docker compose. You may see it in older tutorials, but it behaves similarly.

docker-compose.yml#

Docker compose simplifies the process of building and running containers by putting all the run options in a single docker-compose.yml config file.

As an example, here's this project's docker-compose.yml (we'll cover each section in more detail)

version: "3.9"

services:
  docs:
    image: plebnet-compose
    ports:
      - "8000:8000"
    build:
      context: .
      dockerfile: docs.Dockerfile
    volumes:
      - .:/code
    container_name: rigly-backend-docs
    environment:
      SITE_NAME: ${SITE_NAME}
    command:
      - mkdocs
      - serve
      - -a
      - 0.0.0.0:8000


  app:
    image: my-flask-app:latest
    build:
      context: app
      dockerfile: app.Dockerfile
    depends_on:
      - local_db
    environment:
      - DB_HOST=local_db
      - DB_PORT=${DB_PORT_LOCAL}
      - DB_USER=${DB_USER_LOCAL}
      - DB_PASS=${DB_PASS_LOCAL}
      - DB_NAME=${DB_NAME_LOCAL}
    volumes:
      - ./app:/usr/src/app
    depends_on:
      - local_db
    ports:
      - "8050:8050"


  local_db:
    image: postgres
    restart: always
    volumes:
      - pgdata:/var/lib/postgresql/data/
    environment:
      POSTGRES_USER: ${DB_USER_LOCAL}
      POSTGRES_PASSWORD: ${DB_PASS_LOCAL}
      POSTGRES_DB: ${DB_NAME_LOCAL}
      TZ: ${TZ}
      POSTGRES_HOST_AUTH_METHOD: trust
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "${DB_HOST_LOCAL}"]
      interval: 5s
      timeout: 1s
      retries: 10
    healthcheck:
      test:
        [
          "CMD-SHELL",
          "pg_isready -U ${DB_USER_LOCAL} -d ${DB_NAME_LOCAL} -h ${DB_HOST_LOCAL} -p ${DB_PORT_LOCAL}",
        ]
      interval: 10s
      timeout: 5s
      retries: 5
    hostname: ${DB_HOST_LOCAL}

volumes:
  pgdata:

Build#

We can specify which service to build like this:

docker compose build docs

Or we can build all services at once

docker compose build

Run#

This allows us to run the container like this

docker compose up docs
# container running at localhost:8000 or 0.0.0.0:8000

The above command will automatically build the image if it hasn't already been built.