How to clean Docker container logs?

The best script I found is

sudo sh -c 'truncate -s 0 /var/lib/docker/containers/*/*-json.log'

It cleans all logs and you don't need to stop the containers.

Credit goes to https://bytefreaks.net/applications/docker/horrible-solution-how-to-delete-all-docker-logs


First, if you just need to see less output, you can have docker only show you the more recent lines:

docker logs --since 30s -f <container_name_or_id>

Or you can put a number of lines to limit:

docker logs --tail 20 -f <container_name_or_id>

To delete the logs on a Docker for Linux install, you can run the following for a single container:

echo "" > $(docker inspect --format='{{.LogPath}}' <container_name_or_id>)

Note that this requires root, and I do not recommend this. You could potentially corrupt the logfile if you null the file in the middle of docker writing a log to the same file. Instead you should configure docker to rotate the logs.


Lastly, you can configure docker to automatically rotate logs with the following in an /etc/docker/daemon.json file:

{
  "log-driver": "json-file",
  "log-opts": {"max-size": "10m", "max-file": "3"}
}

That allows docker to keep up to 3 log files per container, with each file limited to 10 megs (so a limit between 20 and 30 megs of logs per container). You will need to run a systemctl reload docker to apply those changes. And these changes are the defaults for any newly created container, they do not apply to already created containers. You will need to remove and recreate any existing containers to have these settings apply.

Tags:

Docker