Configuring Logrotate on CentOS Stream 9: Auto-Compression, Rotation, and Eliminating Disk Full Errors

CentOS tutorial - IT technology blog
CentOS tutorial - IT technology blog

Why Does Your Server Secretly Run Out of Disk Space at Midnight?

A 2 AM disk full alert is a familiar nightmare for sysadmins. The disk hits 100%, the database rejects connections, and the web server crashes. Running df -h reveals the usual suspect: log directories ballooning to dozens of gigabytes.

When CentOS 8 abruptly reached EOL, our team scrambled to migrate to Rocky Linux and set up staging on CentOS Stream 9. Amid the chaotic workload, we forgot to configure log rules for a single Node.js service—and just four days later, a 50GB disk was completely consumed.

Logrotate was built to clean up this mess with four core tasks:

  • Prevent disk exhaustion: Automatically rotate logs on a schedule (daily/weekly) or by size thresholds (e.g., reaching 500MB).
  • Save storage: Compress historical logs using gzip. A 10GB plaintext log file often shrinks down to just 800MB–1.2GB after compression.
  • Automate cleanup: Retain a fixed number of backup rotations (e.g., the last 7 days) and automatically purge older files.
  • Zero service interruption: Seamlessly rotate files so applications continue logging normally without needing a service restart.

Installing and Enabling Logrotate on CentOS Stream 9

Most CentOS Stream 9 templates come with Logrotate pre-installed. However, on minimal installations or stripped-down container images, it’s best to verify:

# Check for the logrotate package
rpm -q logrotate || sudo dnf install -y logrotate

Unlike legacy Linux distributions that relied on daily cron jobs, CentOS Stream 9 manages Logrotate schedules via a systemd timer. Check whether this timer is active:

# Check timer status
sudo systemctl status logrotate.timer

# Enable and start immediately if inactive
sudo systemctl enable --now logrotate.timer

By default, logrotate.timer triggers the service once a day at midnight (00:00:00) with a randomized delay to prevent system I/O spikes.

Hands-On Configuration: Tailored for Nginx and Application Logs

Logrotate separates configuration cleanly into two areas:

  • /etc/logrotate.conf: Contains global server-wide defaults.
  • /etc/logrotate.d/: Houses dedicated rules for specific services (Nginx, MySQL, Redis, custom apps).

An unwritten rule: do not touch the global configuration file. Instead, create separate files inside /etc/logrotate.d/ for easy maintenance and to avoid being overwritten during package updates.

1. Production-Ready Configuration for Nginx

Create a new configuration file at /etc/logrotate.d/nginx:

sudo nano /etc/logrotate.d/nginx

Paste the following optimized configuration:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        if [ -f /run/nginx.pid ]; then
            kill -USR1 $(cat /run/nginx.pid)
        fi
    endscript
}

2. Explaining Each Directive

  • daily: Rotates files once a day.
  • missingok: Silently skips missing log files rather than throwing an error.
  • rotate 14: Retains the 14 most recent archives, equivalent to two weeks of logs.
  • compress: Compresses rotated log files into .gz format.
  • delaycompress: Postpones compressing the most recently rotated file until the next cycle. In other words, .1 remains plaintext, while .2 and older get compressed. This option is critical to prevent logging glitches when a service hasn’t yet released the old file handle.
  • notifempty: Skips rotation if the log file is 0 bytes.
  • create 0640 nginx adm: Immediately creates a new empty log file with 0640 permissions, owned by user nginx and group adm.
  • sharedscripts: Batches commands. Runs the postrotate script only once after all matching log files have been rotated, rather than repeating it for each individual file.
  • postrotate ... endscript: Sends a USR1 signal instructing Nginx worker processes to reopen new log files without interrupting active requests.

3. Size-Based Log Rotation for Backend Services (Go, Node.js, Python)

High-traffic API services often generate logs rapidly. If you only rotate logs daily, your disk might fill up well before the scheduled run. In such scenarios, combine maxsize with copytruncate:

/var/log/my-app/*.log {
    daily
    maxsize 500M
    rotate 7
    compress
    delaycompress
    copytruncate
    missingok
}

Important note on copytruncate: This directive copies the active log file to a backup and then truncates the original file to zero bytes in place. This solution is specifically designed for applications that do not support file descriptor reload signals (such as Go binaries or Node.js apps managed by PM2). The slight trade-off: you might lose a few log lines written during the exact split-second between copy and truncation. For systems with strict audit requirements, prefer streaming logs directly to stdout and managing them with Vector or Fluent Bit.

Testing and Monitoring: Don’t Wait Until Midnight

Once your configuration is written, don’t leave things to chance. Test immediately to ensure the syntax is correct.

1. Test with a Dry Run

The -d (debug) flag simulates the entire process on screen and does not touch real files:

sudo logrotate -d /etc/logrotate.d/nginx

Inspect the output: if you see notices that files do not need rotating or that rules are matched properly, your configuration is valid.

2. Force Rotation Immediately for Verification

Use the -f (force) flag to trigger an immediate live rotation:

sudo logrotate -f /etc/logrotate.d/nginx

After running this command, inspect the log directory:

ls -la /var/log/nginx/

The active log file should reset to zero or a few bytes, alongside a newly created access.log.1 file with proper ownership and permissions. Note: because delaycompress is enabled, .1 remains uncompressed rather than compressed as .gz.

3. Check Run History in the Status File

Logrotate tracks the timestamp of the last rotation for each file in /var/lib/logrotate/logrotate.status. You can quickly inspect it:

cat /var/lib/logrotate/logrotate.status | grep nginx

4. Inspect System Logs on Failures

If you suspect the timer failed to trigger the service, check the systemd journal:

# View the service's most recent execution logs
sudo journalctl -u logrotate.service -n 50 --no-pager

# View the next scheduled trigger time
systemctl list-timers logrotate.timer

Spending 15 minutes properly setting up Logrotate on day one will save you dozens of hours of troubleshooting down the road.

Share: