To determine which Docker container a specific program is running on, you can use the following methods:
Method 1: Check Processes in All Containers Using docker top
-
List all running containers to get their IDs and names:
docker ps -
Check processes in each container for the target program (e.g., nginx):
docker ps –q | xargs –I {} sh –c ‘echo “Container {}:”; docker top {} | grep “nginx”‘ - This loops through all containers and uses docker top to list their processes, then filters for the target program.
Method 2: Find the Program’s PID on the Host and Map to a Container
-
Find the PID of the program on the Docker host:
pgrep –a nginx # Replace “nginx” with your program name -
Check the cgroup of the PID to extract the container ID:
cat /proc/<PID>/cgroup | grep –o –E “docker-[0-9a-f]{64}”
Example:
cat /proc/1234/cgroup | grep –o –E “docker-[0-9a-f]{64}” -
Match the container ID to a running container:
docker ps —no–trunc | grep “<container-id>”
Method 3: Automated Script to Check All Containers
Use this script to loop through containers and check for the program:
1 2 3 4 5 6 7 |
TARGET_PROGRAM=“nginx” # Replace with your program name docker ps —format “{{.ID}} {{.Names}}” | while read –r id name; do if docker top $id | grep –q “$TARGET_PROGRAM”; then echo “Found ‘$TARGET_PROGRAM’ in container: $name ($id)” fi done |
Example Output
1 2 |
Found ‘nginx’ in container: webserver (a1b2c3d4e5f6) |
Key Notes:
- docker top shows processes running inside a container from the host’s perspective.
- Cgroup inspection directly maps a host PID to a container using /proc/<PID>/cgroup.
- Ensure the program name matches exactly (e.g., nginx vs. nginx: worker process).
These methods help identify which container is running a specific program without needing access to the container’s internal tools.