温馨提示×

debian如何轮转nginx日志

小樊
45
2026-09-04 11:06:32
栏目: 智能运维

在 Debian 上轮转 Nginx 日志,通常有两种方式:

  1. 使用系统自带的 logrotate(推荐)
  2. 手动写脚本 + cron

下面重点讲最常用、最标准的方式:logrotate


一、使用 logrotate(Debian 默认已安装)

1. 查看 Nginx 的 logrotate 配置

Debian 安装 Nginx 后,一般会自带:

/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
}

2. 常用参数说明

  • daily:每天轮转
  • rotate 14:保留 14 份
  • compress:压缩旧日志
  • delaycompress:延迟压缩(避免影响正在写入)
  • notifempty:空日志不轮转
  • create:新建日志文件权限
  • postrotate:轮转后让 Nginx 重新打开日志(关键)

二、手动测试 logrotate

测试(不真正执行)

logrotate -d /etc/logrotate.d/nginx

强制执行一次

logrotate -f /etc/logrotate.d/nginx

三、确保 Nginx 能重新打开日志

logrotate 只是移动文件,Nginx 仍会写旧文件,所以需要:

nginx -s reopen

或在 logrotate 中已有:

postrotate
    invoke-rc.d nginx rotate
endscript

Debian 下 nginx rotate 等价于 nginx -s reopen


四、Cron 自动执行

logrotate 由 cron 每日调用:

/etc/cron.daily/logrotate

一般不需要额外配置。

查看最近执行记录:

cat /var/lib/logrotate/status

五、如果想自定义(示例)

例如:

  • 只保留 7 天
  • 每周轮转
  • 不压缩
/var/log/nginx/*.log {
    weekly
    rotate 7
    missingok
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        invoke-rc.d nginx rotate >/dev/null 2>&1
    endscript
}

六、常见问题

1. 日志没轮转?

  • 检查 cron 是否运行
  • 检查 logrotate 状态文件
  • 手动 -f 测试

2. 权限问题?

确保:

/var/log/nginx 属于 www-data:adm

如果你使用的是 Docker / 自定义路径 / systemd 方式安装的 Nginx,我也可以给你对应方案。

0