系统服务
→ 返回 Linux
systemctl 常用命令
# 服务控制
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx # 不中断连接地重载配置
# 状态与自启
systemctl status nginx
systemctl enable nginx # 开机自启
systemctl disable nginx
systemctl is-enabled nginx
systemctl is-active nginx
# 批量操作
systemctl list-units --type=service
systemctl list-units --type=service --failed
systemctl list-unit-files --type=serviceUnit 文件
Unit 文件位于 /etc/systemd/system/(自定义)或 /lib/systemd/system/(系统默认)。
# /etc/systemd/system/myapp.service
[Unit]
Description=My Spring Boot Application
After=network.target
[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/java -jar /opt/myapp/app.jar
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
Environment=SPRING_PROFILES_ACTIVE=prod
EnvironmentFile=/etc/myapp/env
[Install]
WantedBy=multi-user.targetsystemctl daemon-reload # 修改 Unit 文件后必须执行
systemctl enable myapp
systemctl start myappService 类型
| Type | 说明 |
|---|---|
simple | 主进程即为服务进程(默认) |
forking | 父进程 fork 后退出,子进程为主进程 |
oneshot | 短暂执行后退出,常用于初始化脚本 |
notify | 进程主动通知 systemd 启动完成 |
日志查看(journald)
journalctl -f # 实时追踪
journalctl -u nginx -f # 指定服务
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx --since today
journalctl -p err # 只看 error 及以上
journalctl -u nginx -n 100 # 最近 100 行
# 清理日志
journalctl --disk-usage
journalctl --vacuum-size=500M
journalctl --vacuum-time=30dTimer(定时任务,替代 cron)
# /etc/systemd/system/backup.service
[Unit]
Description=Daily Backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true # 错过后补跑
[Install]
WantedBy=timers.targetsystemctl enable --now backup.timer
systemctl list-timerscron(传统定时任务)
crontab -e # 编辑当前用户 crontab
crontab -l # 查看
crontab -r # 删除# 分 时 日 月 周 命令
0 2 * * * /usr/local/bin/backup.sh # 每天 2:00
*/5 * * * * /usr/local/bin/check.sh # 每 5 分钟
0 0 1 * * /usr/local/bin/monthly.sh # 每月 1 日
0 9 * * 1-5 /usr/local/bin/workday.sh # 工作日 9:00
系统级 cron 目录:/etc/cron.d/、/etc/cron.daily/、/etc/cron.weekly/
启动级别(target)
systemctl get-default # 查看默认 target
systemctl set-default multi-user.target # 命令行模式
systemctl set-default graphical.target # 图形模式| Target | runlevel | 说明 |
|---|---|---|
| poweroff | 0 | 关机 |
| rescue | 1 | 单用户救援 |
| multi-user | 3 | 多用户命令行 |
| graphical | 5 | 图形界面 |
| reboot | 6 | 重启 |