在Docker中设置环境变量 [英] Set environment variables in Docker

查看:572
本文介绍了在Docker中设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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.

我创建了一个Dockerfile,该文件生成OpenSuse 42.3的映像。我需要在图像中设置一些环境变量,以便任何从图像启动容器的人都可以使用我编译并放置在图像中的代码。

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.

我创建了一个名为 image_env_setup.sh的外壳文件,其中包含必要的环境变量定义。我还手动将这些环境变量定义添加到了Dockerfile中。

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  \

唯一有效的方法是传递shell文件,以便在容器启动时再次运行。

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

我不认为仅在内部设置shell变量就不会那么困难容器,以便其中的任何条目都可以为用户提供已经定义的容器。

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 项无法修改环境变量(我想您想在 image_env_setup.sh 中设置更多变量)。 Dockerfile中只有 ENV 条目(以及-rcfile 这样的docker选项可以更改环境)。

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).

您还可以决定从 .bashrc 中获取 image_env_setup.sh ,当然。

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

例如,您可以预制一个 .bashrc 并用 COPY ,或执行

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

这篇关于在Docker中设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆