Ubuntu 20.04下logrotate脚本invoke-rc.d失效致Apache日志轮转失败
问题:Logrotate中Apache日志轮转后写入异常,invoke-rc.d失效
环境信息
- Ubuntu 20.04
- Apache 2.4.41
- logrotate 3.14.0
问题现象
原本配置在logrotate的postrotate脚本中重启Apache,但该操作未执行,导致Apache持续写入已轮转的日志文件(后缀为.log.1),且文件无限增大。
默认logrotate配置(/etc/logrotate.d/apache2)
postrotate if invoke-rc.d apache2 status > /dev/null 2>&1; then \ invoke-rc.d apache2 reload > /dev/null 2>&1; \ fi; endscript
invoke-rc.d执行错误
在命令行执行invoke-rc.d apache2 status返回:
# invoke-rc.d apache2 status invoke-rc.d: could not determine current runlevel invoke-rc.d: policy-rc.d denied execution of status. invoke-rc.d: emulating initscript action "status", returning "unknown" #
疑问与需求
- 对
invoke-rc.d功能及配置不了解,求解决建议 - 改用以下简化脚本是否可行?
postrotate apachectl restart endscript
解决方案与说明
关于invoke-rc.d失效的原因与修复
invoke-rc.d是Debian/Ubuntu系中管理服务启停的工具,依赖传统SysV init的运行级别(runlevel)和policy-rc.d策略文件判断操作权限。出现报错的核心原因是:Ubuntu 20.04默认使用systemd替代SysV init,runlevel机制被弱化,同时policy-rc.d限制了服务状态查询操作。
推荐修复方案:替换为systemctl命令
直接使用systemd原生命令systemctl替代invoke-rc.d,适配当前系统环境,稳定性更高:
postrotate if systemctl is-active --quiet apache2; then \ systemctl reload apache2 > /dev/null 2>&1; \ fi; endscript
systemctl is-active --quiet apache2:静默检查Apache是否处于活跃状态,返回值0代表服务正常运行systemctl reload apache2:平滑重载配置,不会中断现有客户端连接,比restart更适合生产环境
关于改用apachectl restart的可行性
直接使用apachectl restart是可行的,但存在两点需要注意:
restart会先停止再启动Apache,会短暂中断所有现有连接,而reload是平滑重载,服务不中断,优先推荐使用reload- 建议添加服务状态检查,避免Apache未运行时执行命令报错:
postrotate if systemctl is-active --quiet apache2; then \ apachectl reload > /dev/null 2>&1; \ fi; endscript
如果可以确认Apache始终处于运行状态,也可以进一步简化为:
postrotate apachectl reload > /dev/null 2>&1 endscript
内容的提问来源于stack exchange,提问作者xgretsch
相关产品推荐
相关产品推荐

