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

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

Detect whether script running inside docker container

问题

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

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

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

  1. #!/bin/sh
  2. if [ ... ]; then # ?
  3. echo 'running in container'
  4. else
  5. echo 'running on host'
  6. fi

答案1

得分: 1

这是一种使用bash的方法:

  1. #!/bin/sh
  2. in_docker(){
  3. local cgroup=/proc/self/cgroup
  4. test -f $cgroup && [ "$(cat $cgroup)" = *:cpuset:/docker/* ]
  5. }
  6. if in_docker; then
  7. echo 'running in container'
  8. else
  9. echo 'running on host'
  10. fi

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

英文:

This is one way with bash :

  1. #!/bin/bash
  2. in_docker(){
  3. local cgroup=/proc/self/cgroup
  4. test -f $cgroup && [[ "$(<$cgroup)" = *:cpuset:/docker/* ]]
  5. }
  6. if in_docker; then
  7. echo 'running in container'
  8. else
  9. echo 'running on host'
  10. fi

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

答案2

得分: 0

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

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

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

英文:

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

  1. #!/bin/sh
  2. if [ -f /.dockerenv ]; then
  3. echo 'running in container'
  4. else
  5. echo 'running on host'
  6. 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:

确定