Logs, Exec & Inspect
Three commands answer most questions about a running container: what is it saying (docker logs), what does it look like inside (docker exec), and how is it configured (docker inspect).
docker logs
Docker captures everything the main process writes to stdout and stderr. That is why container-friendly apps log to the console instead of to files.
docker logs web # everything so far
docker logs -f web # follow (like tail -f)
docker logs --tail 20 web # last 20 lines
docker logs --since 10m web # last 10 minutes
docker logs -t web # add timestampsSample output:
2026/10/17 09:14:02 [notice] 1#1: nginx/1.27.5
2026/10/17 09:14:02 [notice] 1#1: start worker processes
172.17.0.1 - - [17/Oct/2026:09:14:10 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/8.5.0"If docker logs shows nothing although your app is busy, it is probably writing to a file inside the container, or (for Python) buffering its output: set PYTHONUNBUFFERED=1. Official images such as nginx symlink their log files to /dev/stdout and /dev/stderr for this reason.
Log drivers and rotation
By default logs go to the json-file driver: one JSON line per log line under /var/lib/docker/containers/<id>/. Without limits, that file grows forever and can fill the disk of a busy server. Set rotation per container or daemon-wide in /etc/docker/daemon.json:
docker run -d --log-opt max-size=10m --log-opt max-file=3 nginx:1.27{ "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" } }The model shows what rotation does with a stream of log lines: once the current file reaches max-size, it is rotated, and only max-file files are kept.
def write_logs(lines, max_size, max_file):
files = [[]] # files[0] is the current log file
for line in lines:
if sum(len(l) for l in files[0]) + len(line) > max_size:
files.insert(0, []) # rotate: start a new current file
del files[max_file:] # drop the oldest
files[0].append(line)
return files
lines = [f"request {n:02d} 200 OK\n" for n in range(1, 13)]
files = write_logs(lines, max_size=60, max_file=3)
for i, f in enumerate(files):
name = "web-json.log" if i == 0 else f"web-json.log.{i}"
print(f"{name:<15} {[l.split()[1] for l in f]}")
kept = sum(len(f) for f in files)
print(f"kept {kept} of {len(lines)} lines; requests 01-{len(lines) - kept:02d} were rotated away")web-json.log ['10', '11', '12']
web-json.log.1 ['07', '08', '09']
web-json.log.2 ['04', '05', '06']
kept 9 of 12 lines; requests 01-03 were rotated away
Other drivers ship logs elsewhere: local (compact, rotated by default), journald, syslog, fluentd, awslogs, gcplogs. In production, logs usually flow to a central system rather than staying on the host.
docker exec
docker exec runs an extra process inside a running container, sharing its filesystem, network and environment:
docker exec -it web sh # interactive shell
docker exec web cat /etc/nginx/conf.d/default.conf
docker exec -u root web apk add curl # as another user
docker exec -e DEBUG=1 -w /app api python manage.py checkThe exec'd process is not PID 1: when you exit the shell, the container keeps running. Changes you make (installing a tool, editing a file) live only in that container's writable layer and disappear when it is replaced. Use exec to investigate, then fix the image.
docker inspect
docker inspect prints the full JSON description of a container (or image, volume, network). --format takes a Go template to extract one field:
docker inspect web --format '{{.State.Status}}'
docker inspect web --format '{{.NetworkSettings.Networks.bridge.IPAddress}}'
docker inspect web --format '{{json .Mounts}}'
docker inspect web --format '{{.HostConfig.RestartPolicy.Name}}'The model applies simple {{.A.B.C}} paths to a trimmed-down inspect document, the same way the template engine walks the JSON:
import json
inspect = json.loads("""
{
"Name": "/web",
"State": {"Status": "running", "Running": true, "ExitCode": 0, "OOMKilled": false,
"Health": {"Status": "healthy", "FailingStreak": 0}},
"Config": {"Image": "nginx:1.27", "Env": ["PATH=/usr/sbin:/usr/bin", "NGINX_VERSION=1.27.5"]},
"HostConfig": {"RestartPolicy": {"Name": "unless-stopped"}, "Memory": 268435456},
"NetworkSettings": {"Networks": {"bridge": {"IPAddress": "172.17.0.2"}}},
"Mounts": [{"Type": "bind", "Source": "/srv/site", "Destination": "/usr/share/nginx/html", "RW": false}]
}
""")
def template(doc, expr):
path = expr.strip("{} ").lstrip(".").split(".")
value = doc
for key in path:
if not isinstance(value, dict) or key not in value:
return "<no value>"
value = value[key]
return json.dumps(value) if isinstance(value, (list, dict)) else str(value).lower() if isinstance(value, bool) else str(value)
for expr in ["{{.State.Status}}", "{{.State.Health.Status}}", "{{.Config.Image}}",
"{{.HostConfig.Memory}}", "{{.NetworkSettings.Networks.bridge.IPAddress}}",
"{{.State.OOMKilled}}", "{{.Config.User}}"]:
print(f"{expr:<48} {template(inspect, expr)}"){{.State.Status}} running
{{.State.Health.Status}} healthy
{{.Config.Image}} nginx:1.27
{{.HostConfig.Memory}} 268435456
{{.NetworkSettings.Networks.bridge.IPAddress}} 172.17.0.2
{{.State.OOMKilled}} false
{{.Config.User}} <no value>
More helpful commands
| Command | Shows |
|---|---|
docker top web |
processes running in the container |
docker stats |
live CPU, memory, network and disk I/O per container |
docker diff web |
files added (A), changed (C) or deleted (D) in the writable layer |
docker cp web:/etc/nginx/nginx.conf . |
copy files out of (or into) a container |
docker events |
a live stream of engine events: start, die, oom, health_status |
Test yourself
Your Python app prints log lines, but docker logs shows nothing for minutes. What is a likely fix?
- Use
docker execinstead - Set
PYTHONUNBUFFERED=1so output isn't buffered - Publish port 514
- Restart the Docker daemon
What happens to a container if you exit a shell started with docker exec -it web sh?
- The container stops
- The container keeps running; only the exec'd shell ends
- The container is removed
- The image is rebuilt
Why should you set max-size and max-file for the json-file log driver?
- To make logs colourful
- Without them the log file grows without limit and can fill the disk
- To enable docker logs -f
- They are required to start containers