Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

containerized nginx log rotation with logrotate

Nginx doesn't have native log rotation, so an external tool, such as logrotate, is required. Nginx presents a challenge in that the logs have to be reopened post rotation. You can send a USR1 signal to it if the pid is available in /var/run.

But when running in a docker container, the pid file is missing in /var/run (and the pid actually belongs to the host, since it is technically a host process).

If you don't reopen the logs, nginx doesn't log anything at all, though it continues to function otherwise as web server, reverse proxy, etc.

like image 242
Mark Sawers Avatar asked May 02 '17 19:05

Mark Sawers


1 Answers

You can get the process id from the Pid attribute using docker inspect and use kill -USR1 {pid} to have nginx reopen the logs.

Here's the /etc/logrotate.d/nginx file I created:

/var/log/nginx/access.log
{
    size 2M
    rotate 10
    missingok
    notifempty
    compress
    delaycompress
    postrotate
        docker inspect -f '{{ .State.Pid }}' nginx | xargs kill -USR1
    endscript
}
like image 58
Mark Sawers Avatar answered Nov 17 '22 02:11

Mark Sawers