How to define multiple services with slightly different parameters in docker-compose?

Viewed 236

Is there a way to create a list of variables in docker-compose.yml file and create a service for each variable based on template?

E.g. PARAMS=[name_a, name_b, name_c]

Create 3 services:

FOR param IN PARAMS:
    my-service-{param}:
        build: my-image
        container_name: my-container-{param}
        environment:
            NAME: {param}
            SOME_OTHER: ...

This code does not work of course, but the functionality I believe is clear.

1 Answers

There is no such functionality in docker-compose. Maximum you can do is to use environment variables in in combinations with the values.

Having said that, you can use a cli templating engine as mustache-cli and use it to generate the docker-compose.yml.

You can install mustache with

sudo gem install mustache

after installation you need to create a template file docker-compose.mustache and parameter file parameters.yml and combine them in the final file as in this example:

parameters.yml

ports:
  - 10
  - 20
  - 30

docker-compose.mustache

version: "3.9"
services:
{{#ports}}
  web{{.}}:
    build: .
    ports:
      - "50{{.}}:5000"
  redis:
    image: "redis:alpine"
{{/ports}}

Afterwards combine them

~# mustache parameters.yml docker-compose.mustache

version: "3.9"
services:
  web10:
    build: .
    ports:
      - "5010:5000"
  redis:
    image: "redis:alpine"
  web20:
    build: .
    ports:
      - "5020:5000"
  redis:
    image: "redis:alpine"
  web30:
    build: .
    ports:
      - "5030:5000"
  redis:
    image: "redis:alpine"

You can find good tutorial on mustache on this link which can help you with to convert your current docker-compose.yml to the template.

Related