How to install and configure logrotate in Alpine Linux

I installed Alpine Linux as LXD (“Linux Container”). How do I install logrotate to configure log rotating for Nginx server?

You need to use the apk command command to install logrotate. It is an easy to use sysadmin tool that manages large numbers of log files. You can do automatic rotation, compression, removal and much more. This tutorial shows you how to manage log files with logrotate on Alpine Linux running in lxd or VM or any other cloud service.

Install and configure logrotate in Alpine Linux

Type the following command:
# apk add logrotate
Sample outputs:

(1/2) Installing popt (1.16-r7)
(2/2) Installing logrotate (3.14.0-r0)
Executing busybox-1.28.4-r3.trigger
OK: 90 MiB in 82 packages


Your logrotate will get called everyday using a cron job. Here is a default cronjob:
# cat /etc/periodic/daily/logrotate
Sample outputs:

if [ -f /etc/conf.d/logrotate ]; then
	. /etc/conf.d/logrotate
if [ -x /usr/bin/cpulimit ] && [ -n "$CPULIMIT" ]; then
	_cpulimit="/usr/bin/cpulimit --limit=$CPULIMIT"
$_cpulimit /usr/sbin/logrotate /etc/logrotate.conf
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
exit 0

The default logrotate file is located at /etc/logrotate.conf:
# cat /etc/logrotate.conf
Sample outputs:

# see "man logrotate" for details
# rotate log files weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones

# use date as a suffix of the rotated file

# exclude alpine files
tabooext + .apk-new

# uncomment this if you want your log files compressed

# main log file
/var/log/messages {}

# apk packages drop log rotation information into this directory
include /etc/logrotate.d

# system-specific logs may be also be configured here.
For nginx server create/update /etc/logrotate.d/nginx file as follows:
# cat /etc/logrotate.d/nginx
Sample outputs:
/var/log/nginx/*.log {
	  /etc/init.d/nginx --quiet --ifstarted reopen

What this means is that:

  1. /var/log/nginx/*.log – Work on all log files in /var/log/nginx/ directory.
  2. missingok – Do not halt on any error and carries on with the next log file.
  3. sharedscripts – The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated.
  4. postrotate ... script ... endscript – Run this script after the old logs have been compressed. In this case reopen log files for nginx.

This will rotate log file every week. For more info see logrotate(8) man page.