Codementor Events

Docker Compose between files and projects

Published Jan 23, 2023Last updated Jan 27, 2023
Docker Compose between files and projects

Compose supports two methods of sharing a common configuration:

  • Extend an entire Compose file by using multiple Compose files
  • Extend individual services with the extends field

Multiple Compose files

docker-compose.yml

version: '3.4'

services:
  sqldata:
    image: mcr.microsoft.com/mssql/server:2019-latest 

docker-compose.override.yml

version: '3.4'

services:
  sqldata:
    environment:
      - SA_PASSWORD=Pass@word
      - ACCEPT_EULA=Y
    ports:
      - "5433:1433"
    volumes:
      - eshop-sqldata:/var/opt/mssql

volumes:
  eshop-sqldata:
    external: false

To test the override, use the convert command below -

docker compose convert

Output

shared-1.PNG

When you run docker compose up it reads the overrides automatically. Now, it would be nice to use this Compose app in a production environment. So, create another override file.

docker-compose.prod.yml

version: '3.4'

services:
  sqldata:
    environment:
      - SA_PASSWORD=Pass@word
      - ACCEPT_EULA=Y
    ports:
      - "5433:1433"    # Important: In a production environment you should remove the external port

To deploy with this production Compose file you can run

docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d

This deploys all three services using the configuration in docker-compose.yml and docker-compose.prod.yml (but not the dev configuration in docker-compose.override.yml).

Extending services

When defining any service in docker-compose.yml, you can declare that you are extending another service like this:

services:
  web:
    extends:
      file: common-services.yml
      service: webapp
services:
  webapp:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - "/data"
Discover and read more posts from DhananjayKumar
get started