Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional ENV in Dockerfile

Is it possible to conditionally set an ENV variable in a Dockerfile based on the value of a build ARG?

Ex: something like

ARG BUILDVAR=sad ENV SOMEVAR=if $BUILDVAR -eq "SO"; then echo "hello"; else echo "world"; fi 

Update: current usage based on Mario's answer:

ARG BUILD_ENV=prod ENV NODE_ENV=production RUN if [ "${BUILD_ENV}" = "test" ]; then export NODE_ENV=development; fi 

However, running with --build-arg BUILD_ENV=test and then going onto the host, I still get

docker run -it mycontainer bin/bash [root@brbqw1231 /]# echo $NODE_ENV production 
like image 739
Matthew Herbst Avatar asked May 05 '16 18:05

Matthew Herbst


People also ask

Can you use an ENV file in a Dockerfile?

You can use docker run --env-file [path-toenv-file] to provide the environment variables to the container from a . env file.

What does ENV do in Dockerfile?

ENV is mainly meant to provide default values for your future environment variables. Running dockerized applications can access environment variables. It's a great way to pass configuration values to your project. ARG values are not available after the image is built.

Which clauses are the valid entries in Dockerfile?

As such, a valid Dockerfile must start with a FROM instruction. The image can be any valid image – it is especially easy to start by pulling an image from the Public Repositories. ARG is the only instruction that may precede FROM in the Dockerfile .


1 Answers

Yes, it is possible, but you need to use your build argument as flag. You can use parameter expansion feature of shell to check condition. Here is a proof-of-concept Docker file:

FROM debian:stable ARG BUILD_DEVELOPMENT # if --build-arg BUILD_DEVELOPMENT=1, set NODE_ENV to 'development' or set to null otherwise. ENV NODE_ENV=${BUILD_DEVELOPMENT:+development} # if NODE_ENV is null, set it to 'production' (or leave as is otherwise). ENV NODE_ENV=${NODE_ENV:-production} 

Testing build:

docker build --rm -t env_prod ./ ... docker run -it env_prod bash root@2a2c93f80ad3:/# echo $NODE_ENV  production root@2a2c93f80ad3:/# exit docker build --rm -t env_dev --build-arg BUILD_DEVELOPMENT=1 ./ ... docker run -it env_dev bash root@2db6d7931f34:/# echo $NODE_ENV development 
like image 61
Ruslan Kabalin Avatar answered Oct 02 '22 12:10

Ruslan Kabalin