Docker-compose, conditional statements? (e.g. add volume only if condition)

juanmirocks picture juanmirocks · May 17, 2018 · Viewed 23.4k times · Source

I want to add a volume to my service, but only if the final user gave a folder for it. Otherwise, no volume should be mounted, for the already-prepared image has valid data in a default folder.

That is, I want to do something like (pseudocode):

services:

  my_awesome_service:
  
    volumes:
      if ${VARIABLE} => ${VARIABLE}:/app/folder

Are such conditional statements definable in a docker-compose file?

The only way I see to make this possible is to first define a base docker-compose file, which does not have the volume mount, and the call on a second docker-compose file only if the $VARIABLE is defined. This is fine for a single or few conditions, but gets nasty if there are many.

Any solution?

Answer

BMitch picture BMitch · May 17, 2018

Nothing like this currently exists. Options to implement this that I can come up with include:

  1. Make lots of compose file pieces, and merge together the parts you need to build up the final file.

  2. Dynamically generate your compose file. Something like jsonnet may be a good starting point.

  3. Skip compose, and just dynamically generate your docker run command. This starts to lack portability but some use cases are just easier to script yourself.

  4. Submit a PR to the compose and docker/cli github repos to extend the compose functionality. Doing this with a golang template syntax would make the most sense to me.