Alexander Zeitler

Rotating nginx logs using Docker Compose and logrotate

Published on Saturday, December 30, 2023

Photo by Sigmund on Unsplash

Recycling

If you're running nginx in a Docker container, you might want to rotate the logs. Here's how to do it using Docker Compose and logrotate.

Consider the following docker-compose.yml:

version: '3.7'

services:
  nginx:
    image: nginx:1.19.6-alpine
    ports:
      - 80:80
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./logs:/var/log/nginx

The default location for nginx logs is /var/log/nginx. We're mounting the logs directory from the host into the container. This way, we can access the logs from the host.

We can now use logrotate to rotate the logs. Create a logrotate configuration file called that's called like your service in /etc/logrotate.d/, in this case nginx:

touch /etc/logrotate.d/nginx

Add the following content to the file:

/var/opt/deploy/logs/*.log {
  daily
  missingok
  rotate 31
  dateext
  compress
  delaycompress
  notifempty
  sharedscripts
  postrotate
    cd /var/opt/deploy \
      && /usr//bin/docker compose kill -s USR1 nginx
  endscript
}

This will rotate the logs daily, keep 31 days of logs, compress the logs, and send a USR1 signal to the nginx process in the container. This will cause nginx to reopen the log files.

The dateext option will append the date to the rotated log files. For example, access.log will become access.log-20231230.

Make sure to match the path to your logs. In this case, the logs are located in /var/opt/deploy/logs/ on the host. The logs are mounted into the container at /var/log/nginx/. The logs are located in /var/log/nginx/ in the container.

Also make sure to match the path to your docker-compose.yml. In this case, the docker-compose.yml is located in /var/opt/deploy/ on the host.

The postrotate script will change into the directory where the docker-compose.yml is located and send the USR1 signal to the nginx process in the container. This will cause nginx to reopen the log files.

The USR1 signal is sent to the nginx process in the container using docker compose kill. The USR1 signal is not sent to the container itself, but to the process running inside the container. The process running inside the container is nginx.

You can test the log rotation by running logrotate manually:

logrotate -f /etc/logrotate.d/nginx

And that's it. Your nginx logs will now be rotated daily, compressed, and kept for 31 days.

What are your thoughts about "Rotating nginx logs using Docker Compose and logrotate"?
Drop me a line - I'm looking forward to your feedback! email
Imprint | Privacy