目录
Please enable Javascript to view the contents

Linux 基础-服务管理(init / service / systemd)

 ·  ☕ 2 分钟

重要

Linux 服务管理经历三代:init(串行启动)→ service(init 的脚本封装)→ systemd(并行启动 + Unit 统一管理)。2015 年后新发行版默认使用 systemd,向下兼容 System V init。

1. init(System V init)

init 是内核加载后启动的第一个进程(PID=0)。所有服务启动脚本放在 /etc/init.d/ 下,init 按顺序串行执行。

1
/etc/init.d/nginx start

缺点:

  • 启动时间长——服务串行启动
  • 脚本需自行处理启动之外的情况(重启、状态检查等)

2. service

service 命令是对 /etc/init.d/ 脚本的封装,功能与 init 相同。

1
2
3
service nginx start
# 等效
/etc/init.d/nginx start

本质上 service 就是 init 的命令行封装,没有独立的进程管理能力。

3. systemd

systemd 是 2015 年后主流发行版(Ubuntu 15.04+、RHEL 7+)的默认 init 系统。systemd 作为 PID=1 的第一个进程,取代了传统的 init。

核心改进:

对比initsystemd
启动方式串行并行,按依赖关系启动
管理对象仅服务脚本所有系统资源(Unit)
日志各服务独立统一 journald
PID01

3.1 常用命令

系统管理:

命令作用
systemctl reboot重启
systemctl poweroff关机
hostnamectl set-hostname hex设置主机名
timedatectl set-timezone Asia/Shanghai设置时区
localectl set-locale LANG=en_GB.utf8设置语言

服务管理:

1
2
3
systemctl start nginx
systemctl enable nginx
systemctl status nginx

启动耗时分析:

1
2
3
systemd-analyze                    # 总启动时间
systemd-analyze blame              # 每个服务耗时排序
systemd-analyze critical-chain     # 关键路径

用户会话:

1
2
loginctl list-sessions
loginctl list-users

3.2 Unit 概念

systemd 将所有系统资源抽象为 Unit:

Unit 类型后缀用途
Service.service系统服务
Socket.socket进程间通信 socket
Target.target一组 Unit 的集合(类似运行级别)
Timer.timer定时任务(替代 cron)

3.3 日志管理

systemd 使用 journald 统一管理所有 Unit 日志,配置文件 /etc/systemd/journald.conf

1
2
3
journalctl -u nginx          # 查看 nginx 日志
journalctl -f                # 实时跟踪
journalctl --since "1 hour ago"

参考

分享

Hex
作者
Hex
CloudNative Developer