How do docker logs and docker exec assist container debugging?
❓ Interview Prompt: Explain docker logs (stdout/stderr streaming), docker exec interactive shells, and docker inspect for container debugging workflows.
When something goes wrong inside a container, Docker provides several inspection tools without modifying the running application:
docker logs — Capture stdout/stderr:
Containers write output to stdout/stderr, which Docker captures via the json-file log driver by default. You can stream, filter, and tail this output.
docker exec — Execute Commands Inside Running Containers:
Run any command inside a running container's namespace — open a shell, inspect files, test network connectivity, and run one-off commands.
docker inspect — Low-Level Container Metadata:
Returns a full JSON object with the container's configuration, networking, mounts, environment variables, and restart count.
docker stats — Live Resource Metrics:
Real-time CPU%, memory usage/limit, network I/O, block I/O per container.
docker top — Running Processes:
Lists processes running inside the container (like ps aux from the host's perspective).
Code Implementation Example
# Stream logs in real-time (like tail -f)
docker logs -f myapi
# Show last 50 lines with timestamps
docker logs --tail 50 --timestamps myapi
# Filter logs since a timestamp
docker logs --since 2024-01-15T10:00:00 myapi
# Open interactive bash shell inside running container
docker exec -it myapi bash
# or for Alpine images (no bash):
docker exec -it myapi sh
# Run a one-off command without interactive shell
docker exec myapi cat /app/config.json
docker exec myapi env | sort
docker exec myapi curl -s http://localhost:3000/health
# Inspect container config (network, env, mounts)
docker inspect myapi | jq '.[0].NetworkSettings.IPAddress'
docker inspect myapi | jq '.[0].State.RestartCount'
# Live resource usage
docker stats myapi --no-streamdocker logs streams stdout/stderr output; docker exec -it opens an interactive shell inside running containers; docker inspect reveals full configuration metadata.