How to schedule log cleaning in Docker?
There are several ways to schedule the cleaning of Docker logs.
- Utilizing log drivers: Docker supports various log drivers, some of which have the ability to automatically clean up logs. For example, when using the json-file driver, you can set the –log-opt max-size and –log-opt max-file parameters to control the maximum size and number of files for each log file. Once these limits are reached, Docker will automatically clean up old log files.
- Utilize log forwarding tools: Third-party log forwarding tools such as logrotate and logspout can be used to regularly clean up Docker logs. These tools can compress, archive, and delete Docker logs based on set rules.
- Manual cleaning: you can create a script or scheduled task to clean up Docker logs using Docker commands or system commands. For example, you can use the docker logs command to retrieve the container logs, and then use the rm command to delete the log files.
Here is an example of using logrotate to regularly clean up Docker logs.
- Install the logrotate tool.
- Please install logrotate using the command: sudo apt-get install logrotate
- Create a configuration file for logrotate titled /etc/logrotate.d/docker.
- Rotate the log files in the “containers” directory of the Docker folder every day, keeping only 7 archives and compressing them. Each log file should be no larger than 10 megabytes, and any missing files will be ignored. Compression will be delayed until the next rotation, and the log files will be truncated while copying.
- The above configuration file will rotate the log files in the /var/lib/docker/containers/*/*.log directory daily, keeping a maximum of 7 log files with each file being no larger than 10MB, and compressing them. The “copytruncate” parameter is used to ensure that the file handles remain unchanged during log rotation.
- Manually clean up logs by running the logrotate command.
- Please run the command ‘sudo logrotate /etc/logrotate.d/docker’
- You can add the above command to a scheduled task to run regularly and automatically clean up logs.
Please note that the specific steps for log cleanup may vary slightly depending on the operating system, Docker version, etc. The above is just a general example. Please refer to the official instructions of relevant documents and tools for operation.