温馨提示×

debian nginx日志怎么轮转

小樊
44
2026-09-01 09:17:23
栏目: 智能运维

在 Debian 上,Nginx 日志轮转通常不是手动写脚本,而是使用系统自带的 logrotate 工具。下面给你几种常见、推荐的做法。


一、Debian 默认方式(推荐 ✅)

Debian 安装 Nginx 后,一般会自动安装 logrotate,并带有 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
}

手动测试轮转

logrotate -d /etc/logrotate.d/nginx   # 模拟(不实际执行)
logrotate -f /etc/logrotate.d/nginx   # 强制执行

二、确保 Nginx 能重新打开日志(关键)

Nginx 不会自动关闭旧日志文件,轮转后必须让 Nginx 重新打开日志

方式 1(Debian 推荐)

invoke-rc.d nginx rotate

等价于:

nginx -s reopen

方式 2(systemd)

systemctl kill -s USR1 nginx

三、常见轮转策略示例

1️⃣ 每天轮转 + 保留 30 天

/var/log/nginx/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        systemctl kill -s USR1 nginx
    endscript
}

2️⃣ 按大小轮转(如 100M)

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

四、如果是 Docker / 自定义路径

自己加 logrotate 配置

vim /etc/logrotate.d/nginx-custom
/path/to/nginx/logs/*.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    copytruncate
}

⚠️ copytruncate 适合不能发信号的情况(不推荐 Nginx 用)


五、排查常见问题

日志不轮转?

# 查看最后一次执行时间
cat /var/lib/logrotate/status

权限问题?

确保:

  • 日志属主:www-data:adm
  • logrotate 以 root 运行

六、总结(最简方案)

Debian + Nginx 标准做法

  • /etc/logrotate.d/nginx
  • 轮转后 nginx -s reopen
  • 不要手动 rm 或 mv 日志

如果你愿意,可以告诉我:

  • Nginx 版本
  • 是否 Docker
  • 日志路径是否默认

我可以帮你写一份完全适配你环境的 logrotate 配置

0