Log Rotation for Nginx Running on Docker
🎯 Why Log Rotation Matters
Web applications, especially under heavy traffic, produce a large amount of log data through Nginx when it works as a reverse proxy. Over time these logs can grow significantly. If log files are not rotated and managed properly, disk space can fill up, performance can degrade, and services can be interrupted.
In Docker containers, this problem becomes more complex because containers are often short-lived and their internal logs may be isolated from the host system.
🧱 Understanding the Basic Architecture
Applications running inside Docker containers usually write logs either to the filesystem or directly to standard output.
1. File-Based Logging
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
This method stores logs directly on the filesystem. If the files stay inside the container, the host cannot manage them easily. A volume mount is required.
2. Stdout/Stderr Forwarding
access_log /dev/stdout;
error_log /dev/stderr;
With this approach, Docker receives the logs and rotation can be handled by Docker’s log driver.
🔧 Method 1: File-Based Logging + Host Logrotate
Mount Nginx logs to the host:
services:
nginx:
image: nginx:stable
volumes:
- ./logs:/var/log/nginx
Create a logrotate rule:
sudo nano /etc/logrotate.d/nginx-docker
/home/kullanici/nginx-logs/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0640 root adm
sharedscripts
postrotate
docker exec nginx-container-name nginx -s reopen
endscript
}
nginx -s reopen is required because Nginx can continue writing to the old file handle after logrotate renames the file.
docker exec nginx-container-name nginx -s reopen
Alternative:
kill -USR1 $(cat /var/run/nginx.pid)
🛠️ Method 2: Docker Log Driver
services:
nginx:
image: nginx
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
This rotates log files after 10 MB and keeps up to 5 files.
Docker log path:
/var/lib/docker/containers/<container-id>/<container-id>-json.log
🧪 Testing and Validation
docker exec nginx-container-name bash -c "for i in {1..10000}; do echo \"$(date) log test\" >> /var/log/nginx/access.log; done"
sudo logrotate -f /etc/logrotate.d/nginx-docker
Verify that a new log file is created and Nginx continues writing to it.
🧩 Common Issues
| Issue | Explanation |
|---|---|
| logrotate does not run | The log file may not be mounted to the host |
| New log file is not created | nginx -s reopen may not have been executed |
| Disk is still full | Compressed logs may not be cleaned, or the log driver may be misconfigured |
| logrotate fails | PID file may be wrong, or the container may not be reachable |
🔚 Conclusion
Log management for Nginx running in Docker is critical for system stability. Whether using traditional logrotate or Docker’s json-file log driver, rotation should be configured intentionally.
Created: 2025-05-2025