简体   繁体   中英

Set environment variables in 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.

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

你可以将/opt/MyCode/image_env_setup.sh放在/opt/MyCode/image_env_setup.sh的〜/ .bash_profile或〜/ .bashrc中,以便每次进入容器时都有env的设置

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM