
Docker Logs with Systemd
Following our article on the use of containers with Systemd. I would like to clarify a point on the management of logs in containers.
The Docker Rule
The official good practice is not to generate the logs in a file in a
container (/ var / log / container.log
). The rule is therefore to send
all the logs to standard output and let Docker take care of the logs.
This is very practical because you can then consult the logs with docker tools :
docker logs
docker-compose logs
However, be careful to configure your deamon docker because by default it does not perform log rotation which can cause saturation of disk space.
# /etc/docker/daemon.json
{
"log-driver": "json-file",
"log-opts": {
"max-size": "50m",
"max-file":"10",
"compress": "true"
}
}
With SystemD (and JournalD)
In the case of starting containers with systemd
, it may be preferable
to send the logs to journald
by activating the correct log-driver.
# /etc/docker/daemon.json
{
"log-driver": "journald"
}
You can then view the docker logs in journald
directly. (Be careful,
changing the log-driver
does not apply to already created containers)
systemctl restart docker
docker run -d --rm --name hello_world \
alpine sh -c 'while true; do sleep 1.5; echo "hello world"; done'
journalctl CONTAINER_NAME=hello_world
dockerd[944]: hello world
dockerd[944]: hello world
dockerd[944]: hello world
docker stop hello_world
To make your life easier, you can also use tags to filter your logs.
This requires to set the --log-opt
parameter.
For example
for i in $(seq 0 2); do
docker run -d --rm \
--log-opt labels=app --label app=hello \
alpine sh -c "while true; do sleep 1.5; echo \"hello world $i\"; done"
done
journalctl app=hello
dockerd[17136]: hello world 0
dockerd[17136]: hello world 1
dockerd[17136]: hello world 2
dockerd[17136]: hello world 0
dockerd[17136]: hello world 1
dockerd[17136]: hello world 2
docker container ls -f "label=app=hello" -q | xargs docker stop
Now you have a simple but effective solution to manage your docker logs. To help you in the containerization of your historical applications, contact us.