Search code examples
dockerdocker-composedockerfiledocker-machine

Build the docker image with environment variables


so the objective is to have a different image for prod and testing so there are certain variables change accordingly so I need to set env variables during the build.

# Dockerfile
ENV Somename: $value
...

docker build --build-arg Somename=value -t test .

docker run -d -p port:port test

this work flow is not taking the env variables


Solution

  • First you need to consume the build-arg inside you dockerfile using the ARG command.

    FROM alpine
    
    # consume the build arg    
    ARG somename  
    
    # persist the env variable in the built image
    ENV somename=$somename  
    
    # somename will appear as an env variable
    RUN echo $somename 
    RUN env
    

    And running the build command docker build --build-arg somename=hello . will show you an env variable somename=hello