07
服务管理 systemd
systemd · systemctl
装完 nginx 怎么让它"开机自启、挂了自动重启"?答案就是 systemd——现代 Linux 的服务大管家。所有服务(nginx、ssh、数据库)都归它管,命令统一是 systemctl。
systemctl 十一个高频动作
管 nginx 这个服务的全套操作
sudo systemctl start nginx # 现在启动
sudo systemctl stop nginx # 停止
sudo systemctl restart nginx # 重启(改了代码用它)
sudo systemctl reload nginx # 重载配置(不中断连接,更优雅)
sudo systemctl status nginx # 看状态和最近日志
sudo systemctl enable nginx # 开机自启
sudo systemctl disable nginx # 取消开机自启
systemctl is-enabled nginx # 查是否开机自启
systemctl is-active nginx # 查是否正在跑
sudo systemctl mask nginx # 彻底拉黑,谁都别想启动它
sudo systemctl unmask nginx # 解除拉黑
$ systemctl status nginx
● nginx.service - A high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled)
Active: active (running) since Tue 2026-09-15 10:00:00 CST; 1 day ago
Main PID: 881 (nginx)
CGroup: /system.slice/nginx.service
├─881 "nginx: master process"
└─882 "nginx: worker process"
改了配置到底用 restart 还是 reload
reload:重新加载配置,不断现有连接,服务零中断——nginx 改了站点配置用它。restart:彻底杀掉重启,会短暂断一下。拿不准时 restart 最稳,但能 reload 就 reload。
写一个自己的 .service 文件
自己写的程序(比如 Node 服务)也想交给 systemd 管?写一个 unit 文件放到 /etc/systemd/system/:
/etc/systemd/system/myapp.service —— 你自己的服务
[Unit]
Description=My Node App
After=network.target # 网络就绪后再启动我
[Service]
WorkingDirectory=/home/jianma/app
ExecStart=/usr/bin/node app.js # 怎么启动
Restart=always # 挂了自动重启
User=jianma
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target # 在多用户模式下启动
sudo systemctl daemon-reload # 改完 unit 文件必须 reload 一次
sudo systemctl enable --now myapp # 现在启动 + 开机自启,一步搞定
日志 journalctl 与启动分析
systemd 自带的日志
journalctl -u nginx # 看 nginx 的全部日志
journalctl -u nginx -f # 实时跟踪 nginx 日志
journalctl -u myapp --since today # 今天的日志
journalctl -p err # 只看错误级别以上
journalctl --list-boots # 历次启动记录
型unit 类型与 target
.service 普通服务、.socket 套接字(比如 ssh.socket)、.timer 定时任务(现代版 cron)、.target 是"一组服务的集合",相当于老系统的 runlevel(运行级别)。systemctl get-default 看默认 target,multi-user.target 就是"命令行多用户模式",graphical.target 是"带图形界面"。
开机慢怪谁?systemd-analyze blame 列出每个服务启动耗时排名,谁拖后腿一目了然;systemd-analyze 直接告诉你总开机几秒。
开机耗时分析
systemd-analyze # 总开机时间
systemd-analyze blame | head # 最耗时的前 10 个服务
systemctl get-default # 看默认 target
$ systemd-analyze
Startup finished in 2.1s (kernel) + 8.3s (userspace) = 10.4s
$ systemd-analyze blame | head -3
5.232s docker.service
1.104s postgresql.service
0.880s networkd-dispatcher.service
记
本章小结
① 服务就五连:start / stop / restart / reload / status,开机自启 enable。
② 自己的程序写个 .service 文件放 /etc/systemd/system/,daemon-reload 后 enable --now,挂了自动重启。
③ 查日志用 journalctl -u 服务名 -f;开机慢用 systemd-analyze blame 找元凶。