Home > OS >  How to use environment variable in Dockerfile?
How to use environment variable in Dockerfile?

Time:03-05

I am just experimenting with configuring Dockerfile-

FROM ubuntu:latest

RUN apt-get update

RUN echo VERSION_TAG="latest" >> /etc/environment

RUN cat /etc/environment

CMD echo $VERSION_TAG

I built the image using (I was in the req directory) -

docker build -t temp/testing:latest .

Ran it using-

docker run temp/testing:latest

Expected output-

latest

Actual Output-


While building the image, the output of cat /etc/environment

Step 4/5 : RUN cat /etc/environment
 ---> Running in 4grdc7b5165a
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"
VERSION_TAG=latest

It is present inside env variables, still, its value is not being printed, any help will be appreciated.

Note - I want to do it without using
https://docs.docker.com/engine/reference/builder/#env

CodePudding user response:

I need to know the reason.

Docker just exec() the command ENTRYPOINT CMD with nothing in between.

pam is not loaded, so pam_env.so is not loaded, so /etc/environment is not read.

CodePudding user response:

The intention is to use ENV for this, but you can set extra parameters on the command line at docker run with -e

docker run -it -e VERSION='latest' -e NAME='abcd' ubuntu:latest /bin/bash

Alternatively, you can provide a file with each variable per-line

docker run -it --env-file ./my_env ubuntu:latest /bin/bash

You can also do a volume mount with -v, which can smuggle further information and entire paths into the container, including information useful to whatever application you run within it (the intent of Docker containers is normally to run a single application within a known environment)


However, if you're trying to determine if the container is running the latest version of its own tag, this will be problematic
Specifically, the tag may change, but your explicit setting of it won't! .. for such a case, you should consider something else, such as having an outside process which replaces the running container with a new one when the tag changes (so you can assume what's running is always latest) or at some frequency (perhaps every day in the morning)

  • Related