Docker · Containers in practice
How should you collect and manage container logs?
Short answer
Write logs to stdout and stderr and let the runtime collect them. Configure a logging driver with rotation or ship logs to a central system, and never rely on files inside the container.
Docker captures the container's stdout and stderr through a logging driver. The default json-file driver writes them to disk on the host. Without rotation, that file can grow until it fills the disk, which is a common production outage.
docker logs --since 30m --tail 200 api-1
docker run --log-driver json-file --log-opt max-size=10m --log-opt max-file=3 api:1.0.0
docker inspect -f "{{.HostConfig.LogConfig.Type}}" api-1Production logging
- Log structured JSON so fields are queryable
- Include request or trace IDs to correlate across services
- Ship logs to a central system such as Loki, Elasticsearch or a cloud service
- Set retention and rotation explicitly rather than accepting defaults
- Avoid logging secrets and full request bodies with credentials
Writing to a file inside the container hides logs from docker logs and loses them when the container is removed. It also complicates collection because the file lives in a writable layer or a volume.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is writing logs to a file inside the container a problem?
- 2How do you prevent log files from filling the host disk?
- 3What does docker logs actually read?
- 4How would you correlate logs across multiple services?
Say it in the interview
I log to stdout and stderr so the runtime can capture output, and I configure rotation or a central logging driver because the default file can fill the host disk. I use structured logs with request IDs so I can correlate across services, and I avoid writing files inside the container. I also check that the chosen driver still supports the debugging workflow the team relies on.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.