- Method 1
Docker containers typically output their logs to the standard output and standard error streams. Docker provides a few ways to manage container logs, including rotating and truncating logs.
One common way to rotate Docker container logs is to use a log rotation tool like logrotate. Here’s how you can set up log rotation for a Docker container using logrotate:
- Create a logrotate configuration file for your Docker container. For example, create a file named
/etc/logrotate.d/my-container
with the following contents:
/var/lib/docker/containers/*/*/*.log {
rotate 7
daily
compress
missingok
delaycompress
copytruncate
}
This configuration tells logrotate to rotate logs for all Docker containers under /var/lib/docker/containers/
, keep up to 7 rotated logs, rotate logs daily, compress rotated logs, ignore missing log files, delay compression of rotated logs, and use the copytruncate
option to rotate logs without disrupting the container’s logging process.
- Make sure logrotate is installed on your Docker host. You can install logrotate on most Linux distributions using the package manager. For example, on Ubuntu, you can install logrotate by running:
sudo apt-get update
sudo apt-get install logrotate
- Reload logrotate to apply the new configuration by running:
sudo logrotate -vf /etc/logrotate.d/my-container
This will force a log rotation and print the output to the console. You should see a message indicating that the log file was rotated.
- Restart your Docker container to make sure it starts logging to a new file. Docker automatically creates a new log file when the container is restarted.
After you’ve set up log rotation for your Docker container, logrotate will automatically rotate the container’s logs according to the specified configuration. You can customize the log rotation configuration to suit your needs by adjusting the options in the logrotate configuration file.
- Method 2
You can rotate Docker container logs by configuring log rotation settings in the Docker daemon configuration file, which is typically located at /etc/docker/daemon.json
.
Here’s an example configuration that sets up log rotation for Docker containers:
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}
In this example, the log-driver
is set to json-file
, which writes logs to a JSON file on disk. The log-opts
specify the maximum size of each log file (max-size
) and the maximum number of log files to retain (max-file
). In this case, each log file will be limited to 10 megabytes, and a maximum of 3 log files will be kept.
You can also configure log rotation on a per-container basis by specifying --log-opt
options when running the docker run
command. For example:
docker run --log-driver=json-file --log-opt max-size=10m --log-opt max-file=3 my-image
This will configure log rotation for the my-image
container, with the same settings as in the daemon configuration file example above.