skip to Main Content

I need to pass optional, runtime parameter to a command in Docker.

The idea is that if PARAM env variable is set when docker is being run – it should be passed to java command as --key VALUE , and when runtime parameter is not set – it shoulddn’t pass anything – in particular it shouldn’t pass --key parameter name.

I.e. it should run following command if PARAM env variable is set:
/bin/java -jar artifact.jar --key $PARAM

And following if it’s not:
/bin/java -jar artifact.jar

I wanted to use :+ syntax, but it’s resolved during build time, which means it won’t be affected by runtime env variable.

docker build -t test-abc . && docker run -e "PARAM=oooo" test-abc
FROM openjdk:17

ENV PARAM=${PARAM:+"--key $PARAM"}


ENTRYPOINT /bin/java -jar artifact.jar $PARAM

2

Answers


  1. Prepare a script that will correctly handle arguments:

    #!/bin/bash
    args=()
    if [[ -v PARAM ]]; then
       args=(--key "$PARAM")
    fi
    /bin/java -jar artifact.jar "${args[@]}" "$@"
    

    And add it:

    ADD entrypoint.sh /entrypoint.sh
    CMD chmod +x /entrypoint.sh
    ENTRYPOINT /entrypoint.sh
    
    Login or Signup to reply.
  2. If you are using ENTRYPOINT here, and you rewrite it in JSON-array syntax, then you can pass additional arguments to your program after the docker run image-name. (Technically they replace the CMD.)

    # Dockerfile: do use JSON-array syntax; do not attempt to handle options;
    # must use ENTRYPOINT for "container-as-command" layout
    ENTRYPOINT ["java", "-jar", "artifact.jar"]
    
    docker run test-abc --key oooo
    

    You can also write the parameter expansion directly inside the command string. This requires you to use shell-syntax ENTRYPOINT or CMD, and so will essentially forbid you from providing extra options you don’t set up this way. The ${VARIABLE:+value} syntax is supported in the POSIX specification so this should work with all Linux distribution base images, even if they don’t include bash.

    ENTRYPOINT java -jar artifact.jar ${PARAM:=--key "$PARAM"}
    

    BashFAQ/050 has some more syntax suggestions, some of which are bash-specific, but the more detailed ones do require a good understanding of shell splitting and expansions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search