【问题标题】:Agnostic bash check that detects is running inside containers or not检测是否在容器内运行的不可知论 bash 检查
【发布时间】:2020-02-01 14:47:13
【问题描述】:

我正在寻找一种简单但可靠的方法来从 shell (bash) 中检测是否在容器内运行,无论该容器是否恰好在 docker、lxc、pods 下运行...

我需要这个来收集systemctl status "*" 的输出。主要是我想避免像Failed to get D-Bus connection: Operation not permitted 这样的嘈杂故障,这几乎肯定会发生在容器内。

期望的结果是在容器内返回成功并且没有输出,而在其他情况下运行 systemctl。

有几个类似的问题,但我发现没有一个适用于这个用例,大多数答案都是几年前的,而且它们确实无法提供。

【问题讨论】:

标签: bash docker containers podman


【解决方案1】:

我在 docker 运行时使用 if [ -f /.dockerenv ]; then echo "inside container"; else echo "not in container"; fi

【讨论】:

    【解决方案2】:

    在我 100% 同意的@chepner 评论之后,接下来的 KISS 实现呢?

    如果您想更精确并确保避免更多可能的错误,请查看 man systemctl 以及 is-system-running 的返回名称和值。

    # Check if systemctl command is available at all
    if which systemctl 2>&1 > /dev/null; then
        # Check that systemctl isn't offline
        if [ ! "$(systemctl is-system-running)" == "offline" ]; then
          systemctl status '*'
        fi
    fi
    

    测试:

    • 我的本地 ubuntu 机器:状态显示
    • 一个完全运行 systemd 的 docker 容器:显示状态
    • 安装了 systemd 但未运行的 docker 容器:空输出
    • 未安装 systemd 的 docker 容器:空输出

    【讨论】:

    【解决方案3】:

    来自“systemctl status”的消息只是说没有 systemd 守护程序正在运行。一些脚本来检查 - cat /proc/1/cmdline | grep systemd - 在真机上。否则不行。

    但是,像 Redhat "podman --systemd=true" 这样的新方法将克服这一点,并且 systemctl 命令再次起作用。我的 docker-systemctl-replacement 脚本也一样,它在任何地方都可以使用。

    所以我猜你这里有错误的问题。该容器可能以某种方式适用于“systemctl”命令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多