Feedback

Chat Icon

Painless Docker - 2nd Edition

A Comprehensive Guide to Mastering Docker and its Ecosystem

Logs: Container/Daemon Logging, Logging Drivers & Best Practices
60%

Logging Best Practices and Recommendations

Docker containers are ephemeral. They should not store logs inside the container filesystem. Docker containers should be lightweight. They should not include a full logging system inside the image.

Indeed, when you build a container image, the goal is to keep it small, portable, and focused on running the application. Storing logs inside the container makes the image larger, complicates portability, and causes logs to disappear when the container is removed.

So what's the solution to keeping track of logs generated by applications running in containers?

Applications running in containers should always write logs to standard output (stdout) and standard error (stderr). Docker captures these streams and hands them off to the configured logging driver.

Let's look at an example using Nginx to illustrate this concept. Create a Dockerfile with the following content:

# Create a directory for the example
mkdir $HOME/nginx-logging-example
cd $HOME/nginx-logging-example

# Create the Dockerfile
cat > Dockerfile <FROM
ubuntu:latest RUN apt-get update && apt-get install -y nginx CMD ["nginx", "-g", "daemon off;"] EOF

Build and run the image:

cd $HOME/nginx-logging-example

# Build and run the container
docker build -t my_image .

# Remove the old container if it exists
docker rm -f my_container &>/dev/null || true

# Run the new container
docker run --name my_container -d -p 8080:80 my_image

Generate some traffic:

for i in {1..10}; do curl --silent localhost:8080; done

Now check the logs:

docker logs my_container

At this point, you will not see any access logs. By default, Nginx writes its access and error logs to files inside the container. Because these logs are not written to stdout or stderr, Docker doesn't capture them.

You can confirm this by inspecting the log files directly inside the container:

docker exec my_container cat /var/log/nginx/access.log

To make Docker capture the web server logs, the access log must be sent to stdout and the error log to stderr. One common and simple approach is to replace the log files with symbolic links:

RUN ln -sf /dev/stdout /var/log/nginx/access.log \

Painless Docker - 2nd Edition

A Comprehensive Guide to Mastering Docker and its Ecosystem

Enroll now to unlock all content and receive all future updates for free.

Unlock now  $31.99$25.59

Hurry! This limited time offer ends in:

To redeem this offer, copy the coupon code below and apply it at checkout:

Learn More