更新 Centos Docker 映像中的 PATH(替代 Dockerfile ENV)

Update PATH in Centos Docker image (alternative to Dockerfile ENV)

我正在使用 Packer 配置 docker Centos 映像,并使用 bash 脚本而不是 Docker 文件来配置映像(这似乎是 Packer 的方式)。我似乎无法弄清楚的是如何更新 PATH 变量,以便我的自定义二进制文件可以像这样执行:

docker run -i -t <container> my_binary

我试过将 .sh 文件放入 /etc/profile.d/ 文件夹并直接写入 /etc/environment 但 none 似乎生效了。

我怀疑它与 shell Docker 在一次性容器中执行命令时使用的东西有关。我以为是 Bourne Shell 但如前所述,/etc/profile.d//etc/environment 方法均无效。

更新:

据我所知,由于@tgogos 回答中解释的原因,无法更改 运行 容器中的环境变量。但是我不认为这对我来说是个问题,因为在 Packer 完成配置图像后,它会提交图像并将其上传到 Docker Hub。更准确的例子如下:

$ docker run -itd --name test centos:6
$ docker exec -it test /bin/bash
[root@006a9c3195b6 /]# echo 'echo SUCCESS' > /root/test.sh  
[root@006a9c3195b6 /]# chmod +x /root/test.sh
[root@006a9c3195b6 /]# echo 'export PATH=/root:$PATH' > /etc/profile.d/my_settings.sh
[root@006a9c3195b6 /]# echo 'PATH=/root:$PATH' > /etc/environment
[root@006a9c3195b6 /]# exit
$ docker commit test test-image:1
$ docker exec -it test-image:1 test.sh

期待看到 SUCCESS 打印但得到

OCI runtime exec failed: exec failed: container_linux.go:296: starting container process caused "exec: \"test.sh\": executable file not found in $PATH": unknown

更新 2

我已经在 ~/.bashrc 中更新了 PATH,这让我可以执行以下操作:

$ docker run -it test-image:1 /bin/bash
[root@8f821c7b9b82 /]# test.sh 
SUCCESS

然而 运行 docker run -it test-image:1 test.sh 仍然导致

docker: Error response from daemon: OCI runtime create failed: container_linux.go:296: ...

我可以确认我的图像 CMD 设置为“/bin/bash”。那么有人可以解释为什么 运行 docker run -it test-image:1 test.sh 不来源 ~/.bashrc 吗?

/etc/profile 仅在被登录 shell.

调用时被 bash 读取

有关 bash 在启动时读取哪些文件的更多信息,请参阅此 article

编辑:如果您将示例中的最后一行更改为: docker exec -it test bash -lc test.sh 如您所愿。

在以下位置提到了一些要点:

  • How to set an environment variable in a running docker container(同时检查link到相关的github问题)。

其中 @BMitch 提到:

Destroy your container and start a new one up with the new environment variable using docker run -e .... It's identical to changing an environment variable on a running process, you stop it and restart with a new value passed in.

在评论部分,他补充道:

Docker doesn't provide a way to modify an environment variable in a running container because the OS doesn't provide a way to modify an environment variable in a running process. You need to destroy and recreate.

更新:(见评论区)

您可以使用

docker commit --change "ENV PATH=your_new_path_here" test test-image:1