CoreOS - get docker container name by PID?

假如想象 提交于 2020-06-24 07:21:17

问题


I have a list of PID's and I need to get their docker container name. Going the other direction is easy ... get PID of docker container by image name:

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

Any idea how to get the name by PID?


回答1:


Something like this?

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

[EDIT]

Disclaimer This is for "normal" linux. I don't know anything useful about CoreOS, so this may or may not work there.




回答2:


Because @Mitar's comment suggestion deserves to be a full answer:

To get container ID you can use:

cat /proc/<process-pid>/cgroup

Then to convert the container ID to docker container name:

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



回答3:


I use the following script to get the container name for any host PID of a process inside a container:

#!/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"


来源:https://stackoverflow.com/questions/24406743/coreos-get-docker-container-name-by-pid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!