我有一组进程 ID(PID),需要获取它们所在的 Docker 容器名称。反过来,通过镜像名称获取 Docker 容器的 PID 很容易 ...
$ docker inspect --format '{{.State.Pid}}' {SOME DOCKER NAME}
有什么方法可以通过PID获取名称吗?
像这样的内容吗?
$ docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.ID}}' | grep "^${PID},"
[编辑]
免责声明 这适用于“普通”的Linux。我对CoreOS一无所知,因此这可能适用或不适用。
因为@Mitar的评论建议值得成为一个完整的回答:
获取容器ID,您可以使用:
cat /proc/<process-pid>/cgroup
然后将容器ID转换为Docker容器名称:
docker inspect --format '{{.Name}}' "${containerId}" | sed 's/^\///'
也可以将这条命令转换为单行命令
PID=20168; sudo docker ps --no-trunc | grep $(cat /proc/$PID/cgroup | grep -oE '[0-9a-f]{64}' | head -1) | sed 's/^.* //'
#!/bin/bash -e
# Prints the name of the container inside which the process with a PID on the host is.
function getName {
local pid="$1"
if [[ -z "$pid" ]]; then
echo "Missing host PID argument."
exit 1
fi
if [ "$pid" -eq "1" ]; then
echo "Unable to resolve host PID to a container name."
exit 2
fi
# ps returns values potentially padded with spaces, so we pass them as they are without quoting.
local parentPid="$(ps -o ppid= -p $pid)"
local containerId="$(ps -o args= -f -p $parentPid | grep docker-containerd-shim | cut -d ' ' -f 2)"
if [[ -n "$containerId" ]]; then
local containerName="$(docker inspect --format '{{.Name}}' "$containerId" | sed 's/^\///')"
if [[ -n "$containerName" ]]; then
echo "$containerName"
else
echo "$containerId"
fi
else
getName "$parentPid"
fi
}
getName "$1"
cat /proc/<host pid>/cgroup
èژ·هڈ–ه®¹ه™¨ID,然هگژن½؟用docker inspect --format '{{.Name}}' "$containerId" | sed 's/^\///'
ن»ژIDèژ·هڈ–هگچ称م€‚ - Mitardocker inspect --format '{{.Name}}' "$(cat /proc/$PID/cgroup |head -n 1 |cut -d / -f 3)" | sed 's/^\///'
- Markus Kasten
${PID}
在 grep 正则表达式中是什么意思?我刚试了一下,grep 没有起作用。 - wheelerexport PID=123
。或者你可以直接用123
替换${PID}
。 - ivantdocker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Id}} {{.Name}}'
。 - Mert Ülkgün