在 CentOS 下,nohup 本身没有配置文件,它的日志行为是通过启动命令参数和 Shell 重定向来控制的。下面把常见用法和配置思路系统说明一下。
nohup command &
默认行为:
nohup.outnohup.out$HOME/nohup.out⚠️ 不推荐长期依赖默认 nohup.out,日志会无限增长。
nohup command > app.log 2>&1 &
含义:
>:重定向 stdout2>&1:stderr 合并到 stdout&:后台运行✅ 最常用、最推荐
nohup command > app.log 2> error.log &
适合排查错误。
nohup command > /dev/null 2>&1 &
适合不需要日志的程序。
cronolog(按日期切分)nohup command | cronolog "app-%Y%m%d.log" &
安装:
yum install -y cronolog
logrotate(生产推荐 ✅)假设日志路径:
/opt/app/app.log
vim /etc/logrotate.d/app
内容:
/opt/app/app.log {
daily
rotate 7
missingok
notifempty
compress
copytruncate
}
说明:
| 参数 | 含义 |
|---|---|
| daily | 每天轮转 |
| rotate 7 | 保留 7 份 |
| compress | 压缩旧日志 |
| copytruncate | 不重启进程截断日志(适合 nohup) |
✅ nohup 场景必用 copytruncate
如果你用的是 CentOS 7+,更推荐用 systemd 而不是 nohup。
[Unit]
Description=My App
[Service]
ExecStart=/opt/app/start.sh
Restart=always
StandardOutput=append:/var/log/app.log
StandardError=append:/var/log/app_err.log
[Install]
WantedBy=multi-user.target
然后:
systemctl daemon-reload
systemctl start app
systemctl enable app
✅ 自动日志管理、开机自启、崩溃重启
ps -ef | grep command
tail -f app.log
| 场景 | 推荐方式 |
|---|---|
| 临时运行 | nohup command > app.log 2>&1 & |
| 长期运行 | nohup + logrotate |
| 生产环境 | systemd |
| 日志按天 | cronolog / logrotate |
如果你愿意,可以把 具体程序(Java / Python / Shell) 或 CentOS 版本 发我,我可以给你一套可直接用的完整配置。