简体   繁体   中英

docker find container by pid of inside process

I have docker containers. Inside them launched a process. From the host machine the command top outputs pid of all processes launched in within containers.

How can I find a container in which the process with this PID is running?

Thank you.

Thank you @Alex Past and @Stanislav for the help. But I did not get full answers for me. I combined them.
In summary I has got next.

First

pstree -sg <PID>

where PID is the process's PID from the command top

In output I am getting parent PID for the systemd parent process. This PID is docker container's PID.

After I execute

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

where %PID% is this parent PID.

In result I have docker's CONTAINER ID .

That's what I wanted

我想你需要这样的东西:

 docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Name}}' | grep "%PID%"

You can find all parents for this process:

pstree -sg <PID>

This chain will be contains the container

You should be able to use exec against each running container checking if the pid exists. Of course the same process id could exists in more than one container. Here is a small bash script that search for a running process based on the supplied pid in each container:

#!/bin/bash

for container in $(docker ps -q); do
  status=`docker exec $container ls /proc/$1 2>/dev/null`
  if [ ! -z "$status" ]; then
    name=`docker ps --filter ID=$container --format "{{.Names}}"`
    echo "PID: $1 found in $container ($name)"
    break;
  fi
done;

For example:

./find-process.sh 1

You can cycle through the parent processes of the target process using ps -o ppid= and at each step check if the PID of the parent matches one of the containers.

#!/bin/bash

targetpid=$1
parentpid=0

while [ $parentpid != 1 ]; do
    parentpid=$(ps -o ppid= $targetpid)
    docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Name}}' | grep "^$parentpid"
    targetpid="$parentpid"
done

I kinda combined all of these and wrote this two liner. Hopefully useful to someone.

#!/bin/bash
SCAN_PID=`pstree -sg $1 |  head -n 1 | grep -Po 'shim\([0-9]+\)---[a-z]+\(\K[^)]*'`
docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Name}}' | grep "${SCAN_PID}"

First line finds the container entry script and feeds it to the docker inspect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM