8

This github discussion was found. It seems that it is allowed to build a docker image while a certain ENV does not have been set.

How to ensure that the docker build fails if an ENV has not been set?

030
  • 13,235
  • 16
  • 74
  • 173
  • 2
    RUN 'if [ -Z $ENV ]; then exit 1; fi' ? – Tensibai Jul 17 '17 at 09:24
  • Yes, but I would like to see that docker build itself denies it – 030 Jul 17 '17 at 09:26
  • Why that ? An empty of non existent environment variable is the same thing, there's no reason Docker do not allow you to pass an empty variable as it could be a very valid use case... It's up to your responsibility to ensure needed environment variables are there and give an error message back when not. – Tensibai Jul 17 '17 at 09:30
  • 1
    @Tensibai perhaps you could combine both comments and post it as an answer so it could be accepted – 030 Jul 19 '17 at 07:09

3 Answers3

8

An empty of non existent environment variable is the same thing, there's no reason Docker do not allow you to pass an empty variable as it could be a valid use case.

It's up to your responsibility to ensure needed environment variables are there and give an error message back when not.

Something like this:

RUN if [ -z "$AN_ENV_VAR" ]; then echo 'Environment variable AN_ENV_VAR must be specified. Exiting.'; exit 1; fi

You can play with the exit code to automate some actions on failure around your docker build command.

CharlesB
  • 103
  • 3
Tensibai
  • 11,366
  • 2
  • 35
  • 62
4

To error out the build, just add the following with your env variable in the docker-compose file.

${ENV_VAR?Variable ENV_VAR not set}

example:

image: consul:${TAG?Variable TAG not set}
  • Thanks! Used this and it works great. I guess OP asked about Docker and not Docker Compose. Still, this worked great for me as I am using Compose. – Stijn de Witt May 15 '22 at 13:56
1

If the if command construct is very complex for you, you can always simply it like

RUN [ -n "$VAR" ]

This asserts the variable value length is nonzero. If it's empty or not set it'll exit with 1. This is also same as running RUN test -n "$VAR"

I see this error message on my machine

The command '/bin/sh -c [ -n "$VAR" ]' returned a non-zero code: 1