Reduce Docker-compose File length with the YAML Merge Key <<

Mangabo Kolawole - May 3 '22 - - Dev Community

If you are writing a docker-compose file, it can happen to have the same part of the configuration of each container repeated over and over the file.

Let's take this example.

version: '3.7'

services:
  web:
    restart: always
    image: web
    environment:
    - ENVIRONMENT_NAME=local_dev
    - USING_DOCKER_COMPOSE=true
    - DJANGO_SETTINGS_MODULE=sms_mailer.settings
    - DJANGO_CONFIGURATION=Local
    - DJANGO_SECRET_KEY
    - DJANGO_ALLOWED_HOSTS
    - DJANGO_CORS_ORIGIN_WHITELIST
    build:
      context: ./
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    command: /code/run_web.sh

  task_runner:
    restart: always
    image: task_runner
    environment:
    - ENVIRONMENT_NAME=local_dev
    - USING_DOCKER_COMPOSE=true
    - DJANGO_SETTINGS_MODULE=sms_mailer.settings
    - DJANGO_CONFIGURATION=Local
    - DJANGO_SECRET_KEY
    - DJANGO_ALLOWED_HOSTS
    - DJANGO_CORS_ORIGIN_WHITELIST
    build:
      context: ./
      dockerfile: Dockerfile
    ports:
      - "5000:5000"
    command: /code/task_runner.sh   
Enter fullscreen mode Exit fullscreen mode

We have this part of the code repeated two times in the docker-compose file.

environment:
    - ENVIRONMENT_NAME=local_dev
    - USING_DOCKER_COMPOSE=true
    - DJANGO_SETTINGS_MODULE=sms_mailer.settings
    - DJANGO_CONFIGURATION=Local
    - DJANGO_SECRET_KEY
    - DJANGO_ALLOWED_HOSTS
    - DJANGO_CORS_ORIGIN_WHITELIST
  build:
    context: ./
    dockerfile: Dockerfile
Enter fullscreen mode Exit fullscreen mode

Let's use the << YAML keyword to make this file a little bit short.

version: '3.7'

x-web-environment:
  &web-environment
  environment:
    - ENVIRONMENT_NAME=local_dev
    - USING_DOCKER_COMPOSE=true
    - DJANGO_SETTINGS_MODULE=sms_mailer.settings
    - DJANGO_CONFIGURATION=Local
    - DJANGO_SECRET_KEY
    - DJANGO_ALLOWED_HOSTS
    - DJANGO_CORS_ORIGIN_WHITELIST
  build:
    context: ./
    dockerfile: Dockerfile

services:
  web:
    <<: *web-environment
    restart: always
    image: web
    ports:
      - "8000:8000"
    command: /code/run_web.sh

  task_runner:
    <<: *web-environment
    restart: always
    image: task_runner
    ports:
      - "8001:8001"
    command: /code/run_task_runner.sh
Enter fullscreen mode Exit fullscreen mode

And we've just optimized the Docker Compose file.🤟‍

Article posted using bloggu.io. Try it for free.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player