Linux 系统服务管理是运维工程师的核心技能,主要涉及 systemd 和传统的 init 系统。
systemd 服务管理:
- systemctl start service:启动服务
- systemctl stop service:停止服务
- systemctl restart service:重启服务
- systemctl reload service:重新加载配置(不中断服务)
- systemctl status service:查看服务状态
- systemctl enable service:设置服务开机自启
- systemctl disable service:取消服务开机自启
- systemctl is-enabled service:检查服务是否开机自启
- systemctl list-units --type=service:列出所有服务
- systemctl list-unit-files --type=service:列出所有服务文件
- systemctl daemon-reload:重新加载 systemd 配置
服务配置文件:
- 位置:/etc/systemd/system/ 或 /usr/lib/systemd/system/
- 示例:/etc/systemd/system/nginx.service
服务配置文件格式:
ini[Unit] Description=nginx service After=network.target [Service] Type=forking ExecStart=/usr/sbin/nginx ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target
传统 init 服务管理(SysVinit):
- service service start:启动服务
- service service stop:停止服务
- service service restart:重启服务
- service service status:查看服务状态
- chkconfig --list:列出所有服务
- chkconfig service on:设置服务开机自启
- chkconfig service off:取消服务开机自启
服务日志管理:
- journalctl -u service:查看特定服务的日志
- journalctl -u service -f:实时查看服务日志
- journalctl -u service --since today:查看今天的日志
- journalctl -u service --since "2024-01-01" --until "2024-01-02":查看指定时间段的日志
- journalctl -p err:查看错误级别的日志
- /var/log/messages:系统主日志
- /var/log/syslog:系统日志(Debian/Ubuntu)
服务故障排查:
- 检查服务状态:systemctl status service
- 查看服务日志:journalctl -u service
- 检查配置文件:cat /etc/systemd/system/service.service
- 检查端口监听:ss -tulnp | grep service
- 检查进程:ps aux | grep service
- 手动启动测试:直接运行服务的可执行文件
服务优化:
- 调整启动顺序:使用 After 和 Wants 指令
- 设置资源限制:使用 LimitCPU、LimitMEM 等指令
- 配置自动重启:Restart=on-failure、RestartSec=10s
- 优化启动时间:使用 Type=simple 或 Type=notify