I read my Docker container log output using
docker logs -f <container_name>
I log lots of data to the log in my node.js app via calls to console.log()
. I need to clean the log, because it's gotten too long and the docker logs
command first runs through the existing lines of the log before getting to the end. How do I clean it to make it short again? I'd like to see a command like:
docker logs clean <container_name>
But it doesn't seem to exist.
First, if you just need to see less output, you can have docker only show you the more recent lines:
Or you can put a number of lines to limit:
To delete the logs on a Docker for Linux install, you can run the following for a single container:
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: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.In order to do this on OSX, you need to get to the virtual machine the Docker containers are running in.
You can use the walkerlee/nsenter image to run commands inside the VM like so:
Combining that with a simplified version of the accepted answer you get:
Save it,
chmod +x
it, run it.As far as I can tell this doesn't require the container to be stopped. Also, it clears out the log file (instead of deleting it) avoiding errors when doing
docker logs
right after cleanup.You can use logrotate as explained in this article
https://sandro-keil.de/blog/2015/03/11/logrotate-for-docker-container/
This needs to be done before launching the container.
This is not the ideal solution, but until Docker builds in a command to do it, this is a good workaround.
Create a script file
docker-clean-logs.sh
with this content:Grant the execute permission to it:
Stop the Docker container that you want to clean:
Then run the above script:
And finally run your container again:
Credit goes to the user sgarbesi on this page: https://github.com/docker/compose/issues/1083
Solution for a docker swarm service: