如何在 Docker 中为 root 使用 .bashrc

How to .bashrc for root in Docker

我想在 (centos:6) Docker 容器中给我的根用户一个 .bashrc。但是,当我 运行 我的容器时,我发现 .bashrc 还没有来源。这能做到吗?

我的构建命令:

...
RUN touch .bashrc
RUN echo "iptables -t nat -A OUTPUT -d hostA -p tcp --dport 3306 -j DNAT --to hostB" >> .bashrc
...

我的运行命令:

docker run -it --cap-add=NET_ADMIN myImage /bin/bash

bash manpage 指出当 shell 是交互式时读取 .bashrc。因此,如果您想要 bash 读取 .bashrc,您需要使用 -i 启动 bash。

看到:

root@host:~# echo 'echo this is .bashrc' > /tmp/bashrc
root@host:~# docker run -ti -v /tmp/bashrc:/root/.bashrc debian bash -i 
this is .bashrc
root@01da3a7e9594:/#

但是,在容器中像这样执行 bash -i 会覆盖入口点或 cmd,因此将 iptables 命令和最初在 shell 脚本中使用的入口点包装起来可能会更好这将成为您的入口点/cmd。

原来我添加的文件不正确。它应该是 /root/.bashrc 而不仅仅是 .bashrc。将文件添加到正确的位置后,不需要 运行 命令或 CMD。

建造

...
ADD iptables /iptables
RUN touch /root/.bashrc \
 && cat iptables >> /root/.bashrc
...

运行

docker run -it --cap-add=NET_ADMIN myImage /bin/bash