英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论