Sub topic 1
How Docker captures container output
When a containerized program prints a line, Docker has to get that line from the container's isolated process to somewhere you can read it. This chapter covers the first half of that path: how Docker captures a container's output. Later chapters cover what the logging driver does with it, how to rotate it, and how to ship it elsewhere.
Prerequisites
This chapter assumes you can:
- Run containers with
docker run, including the-d,--name, and-tflags. - Use a Linux shell, including redirection such as
2>/dev/nulland>&2. - Read a short JSON object.
You need a Docker Engine on a Linux host to follow the examples that look at files under /var/lib/docker. On Docker Desktop, that directory lives inside a virtual machine, so those examples behave differently.
The two streams every process has
Every Linux process starts with three open file descriptors:
- Descriptor 0 is standard input (stdin).
- Descriptor 1 is standard output (stdout).
- Descriptor 2 is standard error (stderr).
Programs print normal output to stdout and diagnostics to stderr. In a terminal, both streams end up on your screen, so the difference is easy to miss. In a pipeline such as cmd > out.txt, only stdout goes to the file, and stderr still shows on screen.
Docker's logging is built on this convention. For a container, Docker captures what the main process writes to stdout and stderr, and nothing else. It does not read files the application writes, and it does not look at syslog sockets inside the container.
What happens when a container starts
When you run docker run, the Docker daemon (dockerd) asks the container runtime to create the container's main process. It is not attached to your terminal. Docker connects the process's stdout and stderr to pipes that the daemon side can read.
From then on, the sequence is:
- The application writes bytes to descriptor 1 or 2.
- The bytes travel through the pipe to the process that supervises the container (a
containerd-shimprocess on a standard install). - The daemon reads them and splits them into messages. Each message holds the text of one line, the name of the stream it came from, and a timestamp.
- The daemon gives each message to the container's logging driver.
- The driver stores or forwards the message.
The driver is the pluggable part. The capture step is the same no matter which driver you choose. That is why the choice of driver changes where logs live, but not what is in them.
A worked example
Start a container that writes to stdout, to stderr, and to a file:
docker run --name demo alpine sh -c '
echo "to-stdout"
echo "to-stderr" >&2
echo "to-file" > /tmp/app.log
'Now read the logs:
docker logs demoYou see two lines:
to-stdout
to-stderrThe line written to /tmp/app.log is missing. It went into the container's filesystem, which Docker does not read for logging.
Docker also keeps the two streams separate. docker logs replays stdout to its own stdout and stderr to its own stderr, so you can filter them as you would any command:
docker logs demo 2>/dev/nullto-stdoutNow look at what Docker stored. With the default json-file driver, each container gets one file under the daemon's data directory:
CID=$(docker inspect --format '{{.Id}}' demo)
sudo cat /var/lib/docker/containers/$CID/$CID-json.logThe file contains one JSON object per line:
{"log":"to-stdout\n","stream":"stdout","time":"2026-12-04T11:02:10.512345678Z"}
{"log":"to-stderr\n","stream":"stderr","time":"2026-12-04T11:02:10.512398123Z"}The three fields map directly onto the message described above: the text (log), the stream name (stream), and the timestamp (time). The trailing \n is kept as part of the text. Your timestamps will differ.
Only the main process counts
Docker captures the descriptors of the container's main process, which is PID 1 inside the container. Child processes inherit those descriptors by default, so output from a script that PID 1 launches is captured too.
Output is lost in these cases:
- A process redirects its own output. A child started with
> /var/log/job.logwrites to a file, not to the pipe. - A process daemonizes and closes its descriptors. Some older services fork into the background and detach from stdout and stderr. Run them in the foreground instead, for example
nginx -g 'daemon off;'. - The application logs to a file by design. Many programs write
/var/log/app/app.logand never touch stdout.
A common fix is to point the file at the stream. Official images do this. The nginx image links its log files to the container's descriptors:
docker run --rm nginx:alpine ls -l /var/log/nginxlrwxrwxrwx 1 root root 11 ... access.log -> /dev/stdout
lrwxrwxrwx 1 root root 11 ... error.log -> /dev/stderrNGINX still believes it is writing to a file, but each write goes to the pipe Docker reads. You can use the same pattern in your own Dockerfile:
FROM alpine:3.20
RUN ln -sf /dev/stdout /var/log/app.logTTY mode merges the streams
If you start a container with -t (allocate a pseudo-terminal), Docker does not create separate stdout and stderr pipes. Both streams go through the one terminal device. The result is:
- Output from stdout and stderr is interleaved in one stream.
- Docker can no longer tell which stream a line came from, so the
streamfield isstdoutfor everything. docker logs demo 2>/dev/nulldoes not filter errors, because nothing was recorded as stderr.- The terminal translates line endings, so lines may end in
\r\ninstead of\n.
Compare the two modes:
docker run --name notty alpine sh -c 'echo out; echo err >&2'
docker run -t --name withtty alpine sh -c 'echo out; echo err >&2'
echo "--- notty, stderr hidden ---"
docker logs notty 2>/dev/null
echo "--- withtty, stderr hidden ---"
docker logs withtty 2>/dev/nullThe first container prints only out. The second prints both out and err, because the TTY merged them. Use -t for interactive shells, not for services whose logs you want to filter.
Buffering can delay or hide output
Docker reads from the pipe as soon as bytes arrive. The delay often comes from the application. Many runtimes use different buffering when stdout is a pipe than when it is a terminal. A terminal gets line buffering. A pipe often gets block buffering, where output waits until a buffer of several kilobytes fills.
Python is a common example. The program below prints a line every second:
import time
for i in range(5):
print(f"tick {i}")
time.sleep(1)Save it as ticker.py and run it in a container:
docker run -d --name ticker -v "$PWD/ticker.py:/ticker.py:ro" python:3-alpine python /ticker.py
docker logs --follow tickerBecause stdout is a pipe and not a terminal, Python buffers the output. You may see nothing until the program exits, and then all five lines appear at once. Fix it by turning buffering off:
docker rm -f ticker
docker run -d --name ticker -v "$PWD/ticker.py:/ticker.py:ro" python:3-alpine python -u /ticker.py
docker logs --follow tickerThe -u flag makes Python's output unbuffered. Setting PYTHONUNBUFFERED=1 has the same effect. Other languages have their own equivalents, such as flushing explicitly or choosing line-buffered mode in the logging library. A related symptom: if the container crashes, buffered output that was never flushed is lost, so the last lines before a crash are the ones most likely to be missing.
Line splitting and long lines
Docker treats a newline as the end of a message. Two edge cases matter:
- Very long lines. The daemon splits a single line longer than 16 KB (16384 bytes) into several messages. Drivers that support it mark the pieces as partial so they can be reassembled, but a log reader that processes each stored record separately can see one logical line as several. Large JSON log lines, such as dumped stack traces or payloads, are the usual trigger.
- Output without a trailing newline. Text with no newline at the end stays pending until a newline or until the stream closes. A progress bar that rewrites a line with
\rappears as one long line containing carriage returns.
For structured logs, prefer one complete record per line, and keep each record well under 16 KB.
What capture does not do
Capture only moves bytes from the process to the driver. It does not:
- Limit how much is written. A chatty application can produce gigabytes, and the driver stores whatever it receives.
- Rotate or delete anything. Retention is the driver's job, which is why the next chapters cover rotation settings.
- Keep logs after the container is removed. With
json-file, the log file lives in the container's directory and is deleted withdocker rm. - Capture output of
docker exec. Commands run throughdocker execare attached to your terminal for that session and are not part of the container's main log stream.
You can check the last point quickly:
docker run -d --name keeper alpine sleep 300
docker exec keeper sh -c 'echo "from exec"'
docker logs keeperThe docker logs command prints nothing. The text from exec went to your terminal only.
Summary of the capture model
| Question | Answer |
|---|---|
| What does Docker capture? | stdout and stderr of the container's main process and its inheriting children |
| What is each message made of? | Text of one line, stream name, timestamp |
| What is not captured? | Files the app writes, output of `docker exec`, output redirected away from the pipes |
| What changes with `-t`? | The streams are merged, and stream names are lost |
| Who decides where the data goes? | The logging driver, covered in the next chapter |
Clean up the containers from this chapter:
docker rm -f demo notty withtty ticker keeperExercise
An application in a container writes its access log to /var/log/shop/access.log. docker logs shows nothing for it, although the application is running. Give two ways to make those lines appear in docker logs.
Show answer
Docker only captures stdout and stderr of the main process, so a file is invisible to it. Either symlink the file to the stream in the image (ln -sf /dev/stdout /var/log/shop/access.log), as the official nginx image does, or configure the application to write its access log to stdout directly.
Exercise
You run docker run -d --name svc python:3-alpine python app.py. The app prints progress lines, but docker logs svc shows nothing for a long time and then prints many lines at once. What is the likely cause, and what fixes it?
Show answer
Python block-buffers stdout when it is a pipe, so lines wait in the application's buffer until it fills or the process exits. Docker reads the pipe as soon as data arrives, so the delay is not in Docker. Run Python unbuffered with python -u app.py or set PYTHONUNBUFFERED=1.
Exercise
You start a container with docker run -t and then run docker logs <name> 2>/dev/null to hide errors, but the error messages still appear. Why?
Show answer
With -t, Docker allocates a pseudo-terminal and both stdout and stderr go through it as a single stream. Docker cannot tell them apart and records everything as stdout, so redirecting the client's stderr removes nothing. Start the container without -t to keep the streams separate.