Reputation: 282895
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
Reputation: 154
In short,
ENV
to set the environment variables into image. 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:
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
)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
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.
my-env.sh
:#!/bin/bash
export ENV1=XXX
export ENV2=XXX
# ...
entrypoint.sh
:#!/bin/bash
. /my-env.sh
# rest of the things you wanna do when start this image into a container
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"]
docker build -t <repo:tag> .
. Before building the image, your current working directory should contain:
Good luck!
Upvotes: 4