docker-compose use environment variables from .env file docker-compose use environment variables from .env file docker docker

docker-compose use environment variables from .env file


So what you are doing is wrong. Reason being there is environment variable to be passed to Dockerfile while building. So there are two possible solutions

Use Builder Arguments

FROM mybaseimageMAINTAINER Zeinab AbbasimazarARG IPARG JMX_PORTARG WS_PORTRUN echo ${IP}RUN echo ${JMX_PORT}RUN echo ${WS_PORT}

And then pass these build arguments using compose

version: "2"services:  mynode:    build:      context: .      dockerfile: Dockerfile-mynode      args:        - IP=${IP}        - JMX_PORT=${JMX_PORT}        - WS_PORT=${WS_PORT}    environment_file:      - .env    ports:      - "${JMX_PORT}:${JMX_PORT}"      - "${WS_PORT}:${WS_PORT}"

Also you can load environment variables using environment_file. now this is only available when the container is started and they don't apply to your compose file or to your build file.

Also adding the build arguments will only make them available during the build and not during the container start. If you need to do that you need to define the variable twice

FROM mybaseimageMAINTAINER Zeinab AbbasimazarARG IPARG JMX_PORTARG WS_PORTENV IP=${IP} JMX_PORT=${JMX_PORT} WS_PORT=${WS_PORT}RUN env

Copying the environment file

.env

export NAME=TARUN

Dockerfile

FROM alpineCOPY .env /tmp/.envRUN cat /tmp/.env > /etc/profile.d/tarun.sh && chmod +x /etc/profile.d/tarun.shSHELL ["sh","-lc"]RUN env

In the RUN cat /tmp/.env > /etc/profile.d/tarun.sh && chmod +x /etc/profile.d/tarun.sh we create profile file which should be loaded when a shell is executed with profile.

In SHELL ["sh","-lc"] we change default shell from sh -c to sh -l so it can load our profile also.

Output of the last step is

Step 5/5 : RUN env ---> Running in 329ec287a5a6HOSTNAME=e1ede117fb1eSHLVL=1HOME=/rootPAGER=lessPS1=\h:\w\$NAME=TARUNPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binPWD=/CHARSET=UTF-8 ---> 6ab95f46e940

As you can see the environment variable is there.

Note: This .env format cannot be loaded in docker-compose as we have an export statement which is a bash command