YoavKlein
YoavKlein

Reputation: 2715

Set environment variables in Docker container

I want to know if what I'm doing is considered best practice, or is there a better way:

What I want

I want to have a Docker image, which will have some environment variables predefined when run as a container. I want to do that by running some shell script that will export those variables.

What I'm doing

My dockerfile looks like this:

Dockerfile code..
..
..

RUN useradd -m develop
RUN echo ". /env.sh" >> /home/develop/.bashrc

USER develop


Is that a good way?

Upvotes: 0

Views: 837

Answers (2)

David Maze
David Maze

Reputation: 160023

Using the Dockerfile ENV directive would be much more usable than putting environment variables into a file.

ENV SOME_VARIABLE=some-value
# Do not use .bashrc at all
# Do not `RUN .` or `RUN source`

Most ways to use Docker don't involve running shell dotfiles like .bashrc. Adding settings there won't usually have any effect. In a Dockerfile, any environment variable settings in a RUN instruction will get lost at the end of that line, including files you read in using the shell . command (or the equivalent but non-standard source).

For example, given the Dockerfile you show, a docker run invocation like this never invokes a shell at all and never reads the .bashrc file:

docker run the-image env \
  | grep A_VARIABLE_FROM_THE_BASHRC

There are some workarounds to this (my answer to How to source a script with environment variables in a docker build process? describes a startup-time entrypoint wrapper) but the two best ways are to (a) restructure your application to need fewer environment variables and have sensible defaults if they're not set, and (b) use ENV instead of a file of environment-variable settings.

Upvotes: 1

Jayr
Jayr

Reputation: 608

** Check edits

Yes will probably work, if in the right order.

# Add user
RUN useradd -m develop

#switch to user
USER develop

#run script as user.
#RUN echo "./env.sh" >> /home/develop/.bashrc
RUN /bin/bash -c "source ./env.sh"

Although the duplicated RUN useradd is not necessary at all

Upvotes: 0

Related Questions