Reputation: 2343
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.
Upvotes: 26
Views: 31744
Reputation: 21
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.
Upvotes: 2
Reputation: 127
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
Upvotes: 0
Reputation: 2343
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
Upvotes: 52
Reputation: 29991
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
Upvotes: 2
Reputation: 721
You can find all parents for this process:
pstree -sg <PID>
This chain will be contains the container
Upvotes: 4
Reputation: 28096
I suppose you need something like this:
docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Name}}' | grep "%PID%"
Upvotes: 9