如何在Docker容器内感知其他Docker容器的重启状态?
Hey there! Great question—this is absolutely feasible, and there are a couple of reliable ways to pull this off. Let me break down the most practical approaches for you.
方法1:Docker Events + Shell脚本(快速落地)
This is the simplest way to get up and running quickly, using built-in Docker tools and a basic shell script.
Step 1: Grant your container access to the Docker daemon
To let your monitoring container "see" other containers, you need to mount the Docker socket into it. This gives the container permission to interact with the host's Docker daemon:
docker run -d --name container-monitor -v /var/run/docker.sock:/var/run/docker.sock your-custom-image
Pro tip: If you want to avoid running the container as root, you can map the host's
dockergroup ID to the container's user—just add--group-add $(getent group docker | cut -d: -f3)to the run command.
Step 2: Write the restart-monitoring script
Create a shell script (e.g., monitor_restarts.sh) inside your container that listens for restart events and triggers your command:
#!/bin/bash set -e # Filter for restart events (add --filter "name=your-target-container" to watch only one container) docker events --filter 'event=restart' | while read -r raw_event; do echo "[$(date)] Detected container restart: $raw_event" # Replace this line with your actual command /usr/local/bin/your-specified-command --arg1 value1 --arg2 value2 done
Make the script executable with chmod +x monitor_restarts.sh, then set it as your container's entrypoint or run it as a background process.
方法2:Docker SDK + 自定义程序(生产环境推荐)
For more control (like filtering specific containers, handling errors, or adding logging), use the official Docker SDK for Python/Go to build a more robust listener.
Example Python implementation
First, install the Docker SDK in your container:
pip install docker
Then write a Python script to listen for restart events:
import docker import subprocess from datetime import datetime def handle_restart_event(container_name): print(f"[{datetime.now()}] Container {container_name} restarted! Executing command...") # Execute your target command (add error handling as needed) try: result = subprocess.run( ["/path/to/your/command", "arg1", "arg2"], check=True, capture_output=True, text=True ) print(f"Command output: {result.stdout}") except subprocess.CalledProcessError as e: print(f"Command failed with error: {e.stderr}") if __name__ == "__main__": # Connect to the Docker daemon via the mounted socket client = docker.from_env() # Listen for restart events (add filters={'name': 'my-app'} to target a single container) for event in client.events(decode=True, filters={"event": "restart"}): container_name = event["Actor"]["Attributes"]["name"] handle_restart_event(container_name)
This approach lets you add retry logic, integrate with logging systems, or extend functionality easily.
Critical Security Note
Mounting /var/run/docker.sock gives your container root-level access to the host system. Only use this with fully trusted containers, and avoid running the container as root unless absolutely necessary.
内容的提问来源于stack exchange,提问作者Majid Mohsenifar

