dockerdocker-compose

Docker Compose, how to prevent template service to be loaded


I have 2 services that are very similar. I have seen that it is a common practice to give a variable name to one service configuration and use it and extend it in your specific services' configurations.

services:
  backend: &backend
    build:
      context: .
      dockerfile: ./docker/app/DockerFile
    volumes:
      - .:/var/www/apps

  app:
    <<: *backend
    ports:
      - 127.0.0.1:3000:3000
    depends_on:
      - db
      - dashboard_db
      - redis
      - sidekiq

  sidekiq:
    <<: *backend
    depends_on:
      - redis
    command: bundle exec sidekiq

The problem is that when I execute docker compose up the service backend is also up and running, but in my case, I only want the specific services (app and sidekiq) to be up.

Am I using the &variable syntax properly?


Solution

  • This is YAML anchor syntax. This is syntactically correct as you've shown it. Attaching an anchor to a YAML node doesn't cause it to be removed from its parent, though: in the Compose data model, there are three services including backend, and docker-compose up will start all of them.

    The Compose file format allows extension sections (similarly in Compose file format version 3). If you put the anchored object under some other top-level field that isn't services: and starts with x-, then it'll be included in the YAML data model, but Compose won't independently recognize it as a service.

    version: '3.8'
    x-service-templates:  # add this new section
      backend: &backend
        build:
          context: .
          dockerfile: ./docker/app/DockerFile
        volumes:
          - .:/var/www/apps
    services:
      # same as above
      app:
        <<: *backend
        ports: ['127.0.0.1:3000:3000']
        depends_on: [db, dashboard_db, redis, sidekiq]
      sidekiq:
        <<: *backend
        depends_on: [redis]
        command: bundle exec sidekiq