【问题标题】:why does my (centos) docker container not run /etc/bashrc?为什么我的 (centos) docker 容器不运行 /etc/bashrc?
【发布时间】:2019-01-31 18:29:14
【问题描述】:

我正在创建一个 docker 映像,我想在其中挂载我的主目录。但是,我想在实例化时运行其他一些 bashrc 文件。

问题是我无法将此bashrc 文件复制到我的用户的工作目录中,因为我将挂载我的(主机)主目录。我曾尝试因此附加到 /etc/bashrc 或放入 /etc/profile.d 但它永远不会运行。

我的 dockerfile 看起来像这样:

FROM centos:7

RUN adduser -s /bin/bash user -G users
RUN echo "echo /etc/bashrc" >> /etc/bashrc
RUN echo "echo /etc/profile" >> /etc/profile
RUN echo "echo /etc/profile.d/mine.sh" >> /etc/profile.d/mine.sh

USER user
WORKDIR /home/user
ENTRYPOINT [ "/bin/bash" ]

我现在在挂载我的主目录时构建并运行这个容器:

docker build -t devenv .
docker run --rm --volume $HOME:/home/user -it devenv

当我打开控制台时,只有(挂载的).bashrc 运行。但是,如果我运行bash -l(登录shell);然后配置文件运行(但不是 .bashrc)。

bash-4.2$ bash
inside mounted host .bashrc
bash-4.2$ bash -l
/etc/profile.d/mine.sh
/etc/profile
/etc/profile.d/mine.sh
/etc/profile

所以我不知道将在进入控制台时运行的逻辑放在哪里(并且 .bashrc 也应该运行)?为什么 /etc/bashrc 永远不会运行?

EDIT:在centos7虚拟机中运行bash甚至bash -l时; /etc/bashrc 确实会运行...

【问题讨论】:

  • 对。登录 shell(由 -l 选项创建)源 .profile,非登录 shell 使用 .bashrc/etc/bashrc 并不是真正的标准配置文件,需要 (IIRC) 显式启用编译时选项以将其用于非登录交互式 shell。
  • @chepner 你知道我可以使用的任何其他配置文件(不在主目录中)吗?
  • 我建议在.bashrc 的顶部明确采购/etc/bashrc。听起来您的 VM 有一些自定义的 bash 安装,可以使用 /etc/bashrc,但 Docker 映像没有。
  • @chepner 感谢您的提示,这些帮助我找到了解决方法;看我自己的答案..

标签: bash docker


【解决方案1】:

首先;感谢@chepner 向我解释了为什么 /etc/bashrc 不运行。所以我想出了这个很好的解决方法:

  • 强制 bash 在启动时加载 /etc/bashrc
  • /etc/bashrc;添加我的具体配置然后运行~/.bashrc

Dockerfile:

FROM centos:7

RUN adduser -s /bin/bash user -G users
# remove /home/user/.bashrc to avoid infinite loop with /etc/bashrc
# when /home/user is not mounted
RUN rm /home/user/.bashrc
RUN echo "if [ -f ~/.bashrc ]; then . ~/.bashrc; fi" >> /etc/bashrc
RUN echo "echo /etc/bashrc" >> /etc/bashrc
RUN echo "echo /etc/profile" >> /etc/profile
RUN echo "echo /etc/profile.d/mine.sh" >> /etc/profile.d/mine.sh

USER user
WORKDIR /home/user
ENTRYPOINT [ "/bin/bash", "--rcfile", "/etc/bashrc" ]

再次构建并运行给我这个输出:

/etc/profile.d/mine.sh
/etc/bashrc
inside mounted host .bashrc
inside bashrc

CAVEAT:确保删除 docker 镜像中的原始 .bashrc。 ~/.bashrc 的 centos:7 中的默认内容为:

if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

如果没有挂载主目录,则会创建一个无限循环。

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 2020-09-09
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2016-07-22
    相关资源
    最近更新 更多