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.

- 571
- 5
- 17
-
If you have dockerfile read this: https://docs.docker.com/compose/environment-variables/#substitute-environment-variables-in-compose-files – Kasir Barati Apr 08 '22 at 13:44
2 Answers
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
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 "$@"

- 9,973
- 6
- 38
- 47