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
Prepare a script that will correctly handle arguments:
And add it:
If you are using
ENTRYPOINT
here, and you rewrite it in JSON-array syntax, then you can pass additional arguments to your program after thedocker run image-name
. (Technically they replace theCMD
.)You can also write the parameter expansion directly inside the command string. This requires you to use shell-syntax
ENTRYPOINT
orCMD
, 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.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.