Master Nginx Log Rotation with Logrotate: A Complete Step‑by‑Step Guide
This guide explains why nginx logs grow, introduces Logrotate as the Linux log‑management tool, walks through installation, core configuration, custom rotation rules, manual execution, compression options, time‑ and size‑based policies, hourly scheduling, and handling SELinux when rotating nginx logs.
Why Rotate Nginx Logs?
nginx does not split its access.log and error.log automatically, so the files keep growing and can degrade write performance. Using Logrotate provides automated time‑ or size‑based splitting, compression, retention, and post‑rotation actions.
Installing Logrotate
Logrotate is a standard Linux log‑management utility that runs from cron. Install it with the package manager of your distribution: yum install -y logrotate Verify installation:
rpm -ql logrotateBasic Configuration
The main configuration file is /etc/logrotate.conf. A typical minimal setup looks like:
# see "man logrotate" for details
# rotate log files weekly
weekly
# keep 4 weeks of backlogs
rotate 4
# create new (empty) log files after rotating old ones
create
# use date as a suffix of the rotated file
dateext
# include custom configuration directory
include /etc/logrotate.dThis file defines global defaults; individual services add their own rules in /etc/logrotate.d.
Creating a Custom Rotation Rule
Example: rotate all .log files under /opt/logtest daily, keep two versions, and use copytruncate so the original file stays open.
vim test
# test configuration file content
/opt/logtest/*.log {
daily
rotate 2
copytruncate
missingok
}Explanation of the four directives:
daily – split once per day.
rotate – maximum number of rotated files to keep.
copytruncate – copy the current log to a new file, then truncate the original so the process can continue writing.
missingok – ignore errors if the log file is missing.
Manual Rotation and Observation
Force a rotation to see the effect:
# -v shows execution details, -f forces rotation
logrotate -vf /etc/logrotate.d/testPrepare two test files first:
touch test1.log
touch test2.logAfter the first run, Logrotate copies the content to test1.log.1 and truncates the original. Subsequent runs rename older files (e.g., test1.log.1 → test1.log.2) and create a new .1 file, deleting the oldest when the rotate limit is reached.
copytruncate vs. create
copytruncate copies the log then truncates it; a short time gap may cause lost entries and higher I/O for large files.
create renames the original file and immediately creates a fresh file with the same name; the application must be notified to reopen the new file.
When the application supports a reload signal (e.g., nginx), create is preferred.
/var/log/nginx/*.log {
daily
rotate 30
create
sharedscripts
postrotate
if [ -f /run/nginx.pid ]; then
kill -USR1 `cat /run/nginx.pid`
fi
endscript
}Important Notes on Inheritance
If a custom file in /etc/logrotate.d omits parameters like rotate or daily, it does not inherit them from the main config; the missing values default to 0.
When Logrotate is triggered by the system cron, the schedule is defined by the cron entry (usually /etc/cron.daily/logrotate), which runs once per day around 03:05‑03:50 unless the machine is off.
Compressing Rotated Files
Add compress to enable gzip compression and nodelaycompress to compress every rotated file immediately.
/opt/logtest/*.log {
daily
rotate 2
copytruncate
missingok
compress
nodelaycompress
}Use delaycompress if you want the most recent file ( .1) to stay uncompressed.
Time‑Based Rotation
Use dateext (adds a date suffix) together with dateyesterday to name files with the previous day’s date. You can customise the format with dateformat.
/opt/logtest/*.log {
daily
rotate 30
copytruncate
missingok
dateext
dateyesterday
dateformat -%Y-%m-%d
}Size‑Based Rotation
Combine size with a time interval to rotate only when the file exceeds a threshold.
/opt/logtest/*.log {
daily
size 5M
rotate 30
create
missingok
dateext
dateyesterday
}Note that the size check is performed only when the scheduled run occurs.
Hourly Rotation
Logrotate can be run hourly by adding an hourly directive and copying the daily cron script to /etc/cron.hourly:
cp /etc/cron.daily/logrotate /etc/cron.hourly/Custom Execution Time
Instead of relying on the default daily cron, create your own crontab entry. Example: run at 23:59 each night.
crontab -e
# 59 23 * * * /usr/sbin/logrotate -f /etc/logrotate_mytime/nginx
service crond restart # CentOS 6
systemctl restart crond # CentOS 7nginx Specific Rotation Example
Place the following file in /etc/logrotate.d/nginx to rotate Docker‑based nginx logs daily, split when larger than 5 MiB, keep 30 days, and notify nginx after rotation.
/opt/docker-ws/nginx/logs/*.log {
daily
size 5M
rotate 30
copytruncate
notifempty
missingok
dateext
postrotate
if [ -f /run/nginx.pid ]; then
kill -USR1 `cat /run/nginx.pid`
fi
endscript
}If SELinux blocks the rotation, either disable SELinux or adjust the file context:
semanage fcontext -a -t var_log_t "/opt/logtest(/.*)?"
restorecon -Rv /opt/logtestSummary of Logrotate Steps
Logrotate creates rotated files named original.log.N (N starts at 1) and renames older files to increment the suffix.
After rotation, the newest file is .1, the oldest is removed when the rotate limit is exceeded.
Use create when the application can be signalled to reopen logs; otherwise use copytruncate.
Configure compression, date‑based naming, size limits, or hourly execution as needed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
