检测脚本是否在 Docker 容器内运行

huangapple go评论52阅读模式
英文:

Detect whether script running inside docker container

问题

如何使脚本检测是否在容器内运行?

#!/bin/sh
if [ ... ]; then                 # ?
  echo '在容器内运行'
else
  echo '在主机上运行'
fi
英文:

How can a script detect whether it is running inside a container?

#!/bin/sh
if [ ... ]; then                 # ?
  echo 'running in container'
else
  echo 'running on host'
fi

答案1

得分: 1

这是一种使用bash的方法:

#!/bin/sh

in_docker(){
    local cgroup=/proc/self/cgroup
    test -f $cgroup && [ "$(cat $cgroup)" = *:cpuset:/docker/* ]
}

if in_docker; then
  echo 'running in container'
else
  echo 'running on host'
fi

如果您的容器中没有bash,则需要转换为sh语法。

英文:

This is one way with bash :

#!/bin/bash

in_docker(){
    local cgroup=/proc/self/cgroup
    test -f $cgroup && [[ "$(<$cgroup)" = *:cpuset:/docker/* ]]
}

if in_docker; then
  echo 'running in container'
else
  echo 'running on host'
fi

You need to convert to sh syntax if you don't have bash in your container.

答案2

得分: 0

/.dockerenv 文件始终存在于 Docker 容器中,因此我检查它:

#!/bin/sh
if [ -f /.dockerenv ]; then
  echo '在容器中运行'
else
  echo '在主机上运行'
fi

但请注意,该文件是早期 Docker 设计的遗留物,可能在未来的 Docker 版本中被移除。因此,这只是一种解决方法,而不是解决方案。

英文:

The /.dockerenv file always exists in a docker container, so I check that:

#!/bin/sh
if [ -f /.dockerenv ]; then
  echo 'running in container'
else
  echo 'running on host'
fi

But note that file is an artefact of an older docker design, and could be removed in a future docker version. So this is a workaround, rather than a solution.

huangapple
  • 本文由 发表于 2023年6月9日 09:00:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定