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

后端 未结 6 1681
野趣味
野趣味 2021-02-12 02:25

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

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-12 03:00

    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/bash
    if test -z $CONDITION; then
      params="-param1 ${MIPARAM1}"
    else
      params="-param1 ${MIPARAM1} -param2 ${MIPARAM2}"
    fi
    COMMAND_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_defaults
    fi
    

提交回复
热议问题