CoreOS - get docker container name by PID?

后端 未结 3 1939
孤独总比滥情好
孤独总比滥情好 2020-12-30 03:28

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:

$ doc         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 04:21

    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"
    

提交回复
热议问题