Conditional Logic In Dockerfile

Sometimes when running a Dockerfile you need to run some conditional logic based upon an ARG variable. This can be handy in the instance you want to run a production build or development build or need to run an extra step for production, etc.

ARG ENV

RUN if [ "$ENV" = "production" ] ; then yarn client:build:prod ; else yarn client:build ; fi

When running this you need to pass in the argument ENV as part of your docker build command:

docker build -t node-image .  --build-arg ENV=production

Read this Stackoverflow answer about it here. It should be noted that using conditional logic in a Dockerfile forces the Dockerfile to be built each time when normally if nothing changed it would be cached. Because this build-arg is dynamic the Docker build step cannot be cached. In short, using conditional logic in your Dockerfile will slow down the build.

Instagram Post