Skip to content

Instantly share code, notes, and snippets.

@aidin-foroughi
Last active October 6, 2023 20:59
Show Gist options
  • Save aidin-foroughi/bdf5a6b722ea7399f7172aa6b49504d6 to your computer and use it in GitHub Desktop.
Save aidin-foroughi/bdf5a6b722ea7399f7172aa6b49504d6 to your computer and use it in GitHub Desktop.
docker-compose

Some docker compose tips and tricks

For environment variables, use poxis parameter expansion to set defaults:

services: myapp: environment: SOME_VALUE: ${SOME_VALUE:-default-value}

You can define a .env file next to docker-compose to provide the variables

You can use the yaml feature called "anchors" to prevent duplication. e.g. if multiple images use the same environment variables or other parameters

base: &base
    name: Everyone has same name

foo: &foo
    <<: *base
    age: 10

bar: &bar
    <<: *base
    age: 20

But in docker terms, we start these extensions with x-. Like

version: "3.4"

x-app: &default-app
  build:
    context: "."
    args:
      - "APP_ENV=${APP_ENV:-prod}"
  depends_on:
    - "postgres"
    - "redis"
  env_file:
    - ".env"
  image: "nickjj/myapp"
  restart: "unless-stopped"
  stop_grace_period: "3s"
  volumes:
    - ".:/app"

services:
  web:
    <<: *default-app
    ports:
      - "8000:8000"

  worker:
    <<: *default-app

Now we only need to write the common bits once, and multiple services can benefit from it. It’s very handy for setting up common things like logging or various other Docker properties.

You can name the x- properties anything you want as long as it’s valid YAML syntax. These x- properties are called “Extension fields” in Docker Compose’s documentation.

You can simply overwrite the defaults like this"

  worker:
    <<: *default-app
    stop_grace_period: "10s"

To get a GPU inside the docker do:

version: '3'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment