Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set environment variables in Docker

Tags:

bash

docker

I'm having trouble with Docker creating a container that does not have environment variables set that I know I set in the image definition.

I have created a Dockerfile that generates an image of OpenSuse 42.3. I need to have some environment variables set up in the image so that anyone that starts a container from the image can use a code that I've compiled and placed in the image.

I have created a shell file called "image_env_setup.sh" that contains the necessary environment variable definitions. I also manually added those environment variable definitions to the Dockerfile.

USER codeUser
COPY ./docker/image_env_setup.sh /opt/MyCode

ENV PATH="$PATH":"/opt/MyCode/bin:/usr/lib64/mpi/gcc/openmpi/bin"
ENV LD_LIBRARY_PATH="/usr/lib64:/opt/MyCode/lib:"
ENV PS1="[\u@docker: \w]\$ "
ENV TERM="xterm-256color"
ENV GREP_OPTIONS="--color=auto"
ENV EDITOR=/usr/bin/vim

USER root
RUN chmod +x  /opt/MyCode/image_env_setup.sh
USER codeUser
RUN /opt/MyCode/image_env_setup.sh
RUN /bin/bash -c "source /opt/MyCode/image_env_setup.sh"

The command that I use to create the container is:

docker run  -it -d --name ${containerName}  -u $userID:$groupID         \
            -e USER=$USER --workdir="/home/codeUser"            \
            --volume="${home}:/home/codeUser" ${imageName} /bin/bash  \

The only thing that works is to pass the shell file to be run again when the container starts up.

docker start $MyImageTag
docker exec -it $MyImageTag /bin/bash --rcfile /opt/MyCode/image_env_setup.sh

I didn't think it would be that difficult to just have the shell variables setup within the container so that any entry into it would provide a user with them already defined.

like image 230
wandadars Avatar asked Oct 19 '17 16:10

wandadars


1 Answers

RUN entries cannot modify environment variables (I assume you want to set more variables in image_env_setup.sh). Only ENV entries in the Dockerfile (and docker options like --rcfile can change the environment).

You can also decide to source image_env_setup.sh from the .bashrc, of course.

For example, you could either pre-fabricate a .bashrc and pull it in with COPY, or do

RUN echo '. /opt/MyCode/image_env_setup.sh' >> ~/.bashrc
like image 131
AnoE Avatar answered Sep 26 '22 02:09

AnoE