mpen
mpen

Reputation: 282895

Docker RUN persist environment variables?

FROM bitnami/minideb:latest

RUN . /etc/os-release
RUN echo "code1=${VERSION_CODENAME}"
RUN . /etc/os-release && echo "code2=${VERSION_CODENAME}"

When I run this, it prints:

code1=
code2=buster

Is there some way to persist the environment variables between RUN commands and/or a separate command to load environment variables from a file inside the container?

Upvotes: 4

Views: 5209

Answers (1)

AssKicker
AssKicker

Reputation: 154

In short,

  • use ENV to set the environment variables into image.
  • or source your env file at docker run

Here is your Dockerfile:

FROM bitnami/minideb:latest

RUN . /etc/os-release
RUN echo "code1=${VERSION_CODENAME}"
RUN . /etc/os-release && echo "code2=${VERSION_CODENAME}"

According to your Dockerfile, the docker engine will interprete the instructions like this:

  1. RUN . /etc/os-release: starts an intermediate container from image bitnami/minideb:latest, and source the file /etc/os-release, then commit this container to an image with id (let's say ab12)
  2. RUN echo "code1=${VERSION_CODENAME}": starts another intermediate container from the image ab12, which was commited in the previous step. docker engine runs echo "code1=${VERSION_CODENAME}" in this container, then commit it to another image cd34
  3. same as 2. but source and echo is executed in the same intermediate container.

Apparently, in step 1 and 2, the source and echo commands are run in different containers, this is why you failed to get the variables you want.

So, the ENV instruction is a recommanded way to address your problem. But if you really need to read envs from a file, here is a work-around.

  1. prepare a file named my-env.sh:
#!/bin/bash
export ENV1=XXX
export ENV2=XXX
# ...
  1. prepare a file named entrypoint.sh:
#!/bin/bash
. /my-env.sh

# rest of the things you wanna do when start this image into a container
  1. prepare the Dockerfile:
FROM bitnami/minideb:latest

# copy files from local to image
COPY my-env.sh /my-env.sh
COPY entrypoint.sh /entrypoint.sh

# when start this image into a container, execute the following command
ENTRYPOINT ["bash", "/entrypoint.sh"]
  1. build image by docker build -t <repo:tag> .. Before building the image, your current working directory should contain:
    • my-env.sh
    • entrypoint.sh
    • Dockerfile

Good luck!

Upvotes: 4

Related Questions