温馨提示×

debian nginx日志如何轮转

小樊
34
2026-09-13 07:49:21
栏目: 智能运维

在 Debian 上,Nginx 日志轮转通常通过 logrotate 来实现。下面从「原理 → 默认配置 → 自定义 → 手动测试」一步步说明。


一、Debian 中 Nginx 日志轮转原理

Debian 安装 Nginx 后,会自动安装 logrotate,并提供一个配置文件:

/etc/logrotate.d/nginx

该文件由 logrotate 每天定时执行(由 /etc/cron.daily/logrotate 触发)。


二、默认的 Nginx logrotate 配置

查看默认配置:

cat /etc/logrotate.d/nginx

典型内容如下(不同版本略有差异):

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi \
    endscript
    postrotate
        invoke-rc.d nginx rotate >/dev/null 2>&1
    endscript
}

关键参数说明

参数 含义
daily 每天轮转
rotate 14 保留 14 个旧日志
compress 压缩旧日志
delaycompress 延迟一次压缩(方便排查)
notifempty 空日志不轮转
create 新建日志文件及权限
postrotate 通知 Nginx 重新打开日志

重点postrotate 中的 nginx rotatekill -USR1 是必须的,否则 Nginx 还会写旧文件。


三、常见自定义需求

1️⃣ 改成按大小轮转(例如 100M)

/var/log/nginx/*.log {
    size 100M
    rotate 10
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        systemctl kill -s USR1 nginx
    endscript
}

2️⃣ 只保留 7 天日志

daily
rotate 7

3️⃣ 单独轮转 access / error 日志

/var/log/nginx/access.log {
    daily
    rotate 30
    compress
    postrotate
        systemctl kill -s USR1 nginx
    endscript
}

/var/log/nginx/error.log {
    daily
    rotate 14
    compress
}

四、立即测试 logrotate(不真正执行)

logrotate -d /etc/logrotate.d/nginx

✅ 用于检查配置是否正确(dry run)


五、强制立即轮转(调试用)

logrotate -f /etc/logrotate.d/nginx

执行后查看:

ls -lh /var/log/nginx/

应看到类似:

access.log
access.log.1
access.log.1.gz

六、确认 Nginx 是否重新打开日志

ls -i /var/log/nginx/access.log

轮转后 inode 改变是正常的(Nginx 已 reopen)


七、常见问题

❌ 日志不轮转?

  • 检查 logrotate 是否在运行
    systemctl status logrotate
    
  • 检查 cron 是否启用
    ls /etc/cron.daily/logrotate
    

❌ Nginx 还在写旧日志?

确认 postrotate 里有:

systemctl kill -s USR1 nginx

kill -USR1 $(cat /run/nginx.pid)

如果你愿意,我可以:

  • 帮你写一份 生产环境推荐配置
  • 或针对 Docker / 自定义路径 Nginx 给方案

0