6

I have a container image that requires an environment variable to be set in order to run. But if run with -d, unless the container is monitored, the person running the container won't notice something is missing. Is there a way that docker [container] run checks that an environment variable is given to the container before starting it.

1

2 Answers 2

3

In detach mode it not possible to print message that env is required, in your word when running with -d, but you can try a workaround:

Dockerfile

FROM alpine
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]

entrypoint.sh

#!/bin/sh
echo "starting container $hostname"
if [ -z "$REQUIRED_ENV" ]; then
  echo "Container failed to start, pls pass -e REQUIRED_ENV=sometest"
  exit 1
fi
echo "starting container with $REQUIRED_ENV"
#your long-running command from CMD
exec "$@"

So when you run with

docker run -it --name envtest  --rm env-test-image 

it will exit with the message

starting container 
Container failed to start, pls pass -e REQUIRED_ENV=sometest

The workaround with detach mode

docker run -it --name envtest  -d --rm env-test-image && docker logs envtest
3

No: there is currently no way to make Docker aware of "dependencies" in the form of environment variables. This answer is for those who actually came here just looking for a canonical way to exit an entrypoint script in case of missing values.


A POSIX shell takes the option -u (error when expanding unset variables) and -e (exit the shell when any statement returns an error/non-zero exit code). We also have : to evaluate-but-not-invoke an expression. Putting these together, we should be able to make an entrypoint.sh that works irrespective of sh-implementation like this:

#!/bin/sh -e -u

( : $USERNAME )
( : $PASSWORD ) 

exec "$@"

which will exit the script with an error akin to PASSWORD: parameter not set.

Another way of doing the same thing, but in context of the original example with a custom error message, could make use of the "Display Error if Null or Unset" operator (${parm:?error}) and look something like so:

#!/bin/sh
echo "starting container $hostname"
( : ${REQUIRED_ENV?"pls pass -e REQUIRED_ENV=sometest"} ) || exit 1
echo "starting container with $REQUIRED_ENV"
#your long-running command from CMD
exec "$@"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.