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
(1/2) Installing popt (1.16-r7)
(2/2) Installing logrotate (3.14.0-r0)
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
if [ -f /etc/conf.d/logrotate ]; then
if [ -x /usr/bin/cpulimit ] && [ -n "$CPULIMIT" ]; then
$_cpulimit /usr/sbin/logrotate /etc/logrotate.conf
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
The default logrotate file is located at /etc/logrotate.conf:
# cat /etc/logrotate.conf
# see "man logrotate" for details
# rotate log files weekly
# keep 4 weeks worth of backlogs
# 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
# apk packages drop log rotation information into this directory
# 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
/etc/init.d/nginx --quiet --ifstarted reopen
What this means is that:
- /var/log/nginx/*.log – Work on all log files in /var/log/nginx/ directory.
- missingok – Do not halt on any error and carries on with the next log file.
- 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.
- 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.