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

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


Poor man's solution:

    volumes:      ${VARIABLE:-/dev/null}:/app/folder

Or:

    volumes:      ${VARIABLE:-/dev/null}:${VARIABLE:-/tmp}/app/folder


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.


Yeah, I do not think docker-compose's format supports conditional statements.

However, two solutions could be:

  1. Pass a "complex" (list-like) variable to the docker-compose such as in this example:

docker-compose.yaml:

command: ${COMMAND_PARAMS}

bash:

#!/bin/bashif test -z $CONDITION; then  params="-param1 ${MIPARAM1}"else  params="-param1 ${MIPARAM1} -param2 ${MIPARAM2}"fiCOMMAND_PARAMS=$params docker-compose up

(credits goes to original poster on github, @shin-)

  1. Prepare the default folder in the docker image in a folder named something like folder_defaults, then have the volume always defined in docker-compose.yml, but then finally, have an internal script in the docker image that checks whether the volume folder is empty, and if so ln -s to the folder_defaults; otherwise leave it as it is.

Example of the conditional script:

if [ -z "$(ls -A /a/folder)" ]; then  do something... using /a/folder_defaultsfi