CoreOS - 通过 PID 获取 Docker 容器名称?

19

我有一组进程 ID(PID),需要获取它们所在的 Docker 容器名称。反过来,通过镜像名称获取 Docker 容器的 PID 很容易 ...

$ docker inspect --format '{{.State.Pid}}' {SOME DOCKER NAME}

有什么方法可以通过PID获取名称吗?

4个回答

25

像这样的内容吗?

$ docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.ID}}' | grep "^${PID},"

[编辑]

免责声明 这适用于“普通”的Linux。我对CoreOS一无所知,因此这可能适用或不适用。


1
如果只需要 Docker 名称,可以在末尾添加 | awk '{print $2}' :) 谢谢 - Nimrod007
2
对于我的当前Docker版本,我不得不将{{.ID}}更改为{{.Id}},似乎Docker检查输出略有变化! - David
1
${PID} 在 grep 正则表达式中是什么意思?我刚试了一下,grep 没有起作用。 - wheeler
@wheeler,你要找的是PID。例如,如果你要找的是PID 123,那么在运行上面的命令之前,你可以export PID=123。或者你可以直接用123替换${PID} - ivant
要获取完整的列表和名称,请使用 docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Id}} {{.Name}}' - Mert Ülkgün

15

因为@Mitar的评论建议值得成为一个完整的回答:

获取容器ID,您可以使用:

cat /proc/<process-pid>/cgroup

然后将容器ID转换为Docker容器名称:

docker inspect --format '{{.Name}}' "${containerId}" | sed 's/^\///'

5

也可以将这条命令转换为单行命令

PID=20168; sudo docker ps --no-trunc | grep $(cat /proc/$PID/cgroup | grep -oE '[0-9a-f]{64}' | head -1) | sed 's/^.* //'


PID=20168; sudo docker ps --no-trunc | grep $(grep -oE '[0-9a-f]{64}' /proc/$PID/cgroup | head -1) | sed 's/^.* //' - Ritschie
sudo docker ps --no-trunc | grep $(head -1 /proc/$PID/cgroup | grep -oE '[0-9a-f]{64}') | sed 's/^.* //'简单解释一下:--no-trunc 选项会显示一个包含数字和字符“a”到“f”的 64 位哈希值的容器 ID。grep -oE '[0-9a-f]{64}' 命令会精确匹配 64 位哈希值,并只打印出哈希值。 - Ritschie
请勿将附加信息作为评论添加到您的答案中。相反,请使用格式化文本编辑您的答案,将此信息包含在答案中。 - Hoppeduppeanut

2
我使用以下脚本来获取容器中任何进程的主机PID的容器名称:
#!/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"

你使用的是哪个版本的Docker? - Mitar
4
و‚¨è؟کهڈ¯ن»¥ن½؟用cat /proc/<host pid>/cgroupèژ·هڈ–ه®¹ه™¨ID,然هگژن½؟用docker inspect --format '{{.Name}}' "$containerId" | sed 's/^\///'ن»ژIDèژ·هڈ–هگچ称م€‚ - Mitar
1
使用 @Mitar 的方法,以下是一行命令:docker inspect --format '{{.Name}}' "$(cat /proc/$PID/cgroup |head -n 1 |cut -d / -f 3)" | sed 's/^\///' - Markus Kasten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接