Set environment variables in Docker

2020-07-18 06:41发布

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.

标签: bash docker
2条回答
家丑人穷心不美
2楼-- · 2020-07-18 07:29

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
查看更多
ら.Afraid
3楼-- · 2020-07-18 07:35

you can put /opt/MyCode/image_env_setup.sh in ~/.bash_profile or ~/.bashrc of the container so that everytime you get into the container you have the env's set

查看更多
登录 后发表回答