在线咨询 400-826-1668
回到顶部
ARTICLE DETAIL

资讯详情

深耕国风建站与运营引流的一线实战洞察。

Linux命令-systemctl(Systemd 服务管理核心工具)

Linux命令-systemctl(Systemd 服务管理核心工具) Linux命令-systemctlSystemd 服务管理核心工具 简介 语法⚙️ 选项 常用命令Command1. Unit 管理最常用2. 系统状态控制需要 root3. 信息查询 实战示例示例 1查看服务状态status 输出解读示例 2启动/重启/重载一个服务示例 3查看所有失败的服务故障排查必备示例 4list-units / list-unit-files 信息查询示例 5修改 unit 文件后重载daemon-reload示例 6用户级 systemd无需 root⚠️ 注意事项 总结 相关命令快速参考systemctl是现代 Linux 发行版RHEL 7、CentOS 7、Ubuntu 16.04、Debian 8中用于管理systemd 系统和服务管理器的核心命令行工具。它取代了传统的 SysVinit 的service和chkconfig命令统一管理系统服务service、挂载点mount、设备device、套接字socket、定时器timer等所有单元Unit是 Linux 系统管理员必须熟练掌握的命令之一。本文中所有示例在 CentOS 7 / Ubuntu 22.04 实测通过部分输出可能因发行版与版本略有差异。 简介项目说明命令全称system control所属包systemdCentOS/RHEL:systemd-sysvDebian/Ubuntu:systemd守护进程PID 1 的systemd配置文件/etc/systemd/system/*.service、/usr/lib/systemd/system/*.service日志查看配合journalctl用户权限大部分子命令需要root普通用户只能查询status/is-active等只读子命令配置文件目录优先级/etc/systemd/system/run/systemd/system/usr/lib/systemd/system核心概念 Unit单元systemd 把所有可管理的资源都抽象为Unit常见类型后缀含义如下后缀含义示例.service系统服务nginx.service.socket套接字docker.socket.target目标多 unit 组合multi-user.target.timer定时器logrotate.timer.mount挂载点home.mount.path路径监控myapp.path.slice资源切片user-1000.slice 语法systemctl[选项...]命令[单元名...]⚙️ 选项选项说明-a/--all显示所有加载/未加载的单元含 inactive-t TYPE/--typeTYPE仅列出指定类型service/socket/timer…--stateSTATE过滤状态active/inactive/failed/running…-H HOST远程操作需开启 SSH 服务并配置SYSTEMD_REMOTE_HOST--user管理当前用户的 systemd 实例无需 root--no-pager不调用分页器脚本中常用--failed列出失败的单元list-units --failed的简写--no-legend不输出表头-q/--quiet静默模式--rootPATH以指定目录为根查找 unit 文件chroot 场景--now配合enable使用立即启动并设置开机自启 常用命令Command按功能分为三大类熟练后优先记忆英文子命令1. Unit 管理最常用子命令作用示例start UNIT启动单元systemctl start nginxstop UNIT停止单元systemctl stop nginxrestart UNIT重启先 stop 再 start会中断服务systemctl restart nginxreload UNIT重新加载配置不中断进程不重启systemctl reload nginxreload-or-restart UNIT支持 reload 则 reload否则 restartsystemctl reload-or-restart nginxstatus UNIT查看状态默认含最近日志systemctl status nginxtry-restart UNIT仅在运行时重启systemctl try-restart nginxenable UNIT设置开机自启创建软链systemctl enable nginxdisable UNIT取消开机自启systemctl disable nginxenable --now UNIT立即启动 开机自启systemctl enable --now nginxis-active UNIT是否正在运行systemctl is-active nginxis-enabled UNIT是否开机自启systemctl is-enabled nginxis-failed UNIT是否失败systemctl is-failed nginxmask UNIT屏蔽无法手动/自动启动systemctl mask nginxunmask UNIT取消屏蔽systemctl unmask nginxlist-dependencies UNIT显示依赖关系systemctl list-dependencies nginxedit UNIT创建 drop-in 片段在/etc/systemd/system/UNIT.d/systemctl edit nginxcat UNIT显示完整 unit 文件含 drop-insystemctl cat nginxshow UNIT显示所有属性systemctl show nginx2. 系统状态控制需要 root子命令作用daemon-reload重新加载所有 unit 文件修改 unit 后必做halt停机不切断电源poweroff关机切断电源reboot重启suspend挂起到内存hibernate挂起到磁盘rescue进入救援模式单用户emergency进入紧急模式只读根default切换到默认 target3. 信息查询子命令作用list-units列出已加载的单元默认行为list-unit-files列出所有已安装的 unit 文件list-sockets列出 socket 单元list-timers列出定时器替代 crontab 查看list-jobs列出正在运行的任务get-default查看默认启动 targetset-default TARGET设置默认启动 target 实战示例示例 1查看服务状态status 输出解读# 查看 nginx 服务的完整状态$sudosystemctl status nginx ● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded(/usr/lib/systemd/system/nginx.service;enabled;vendor preset: disabled)Active: active(running)since Mon2024-01-1510:23:45 CST;3days ago Process:1234ExecStartPre/usr/sbin/nginx-t(codeexited,status0/SUCCESS)Process:1235ExecStart/usr/sbin/nginx(codeexited,status0/SUCCESS)Main PID:1235(nginx)Tasks:5(limit:23512)Memory:14.8M CGroup: /system.slice/nginx.service ├─1235 nginx: master process /usr/sbin/nginx ├─1236 nginx: worker process └─1237 nginx: worker process Jan1510:23:45 web01 systemd[1]: Starting The nginx HTTP and reverse proxy server... Jan1510:23:45 web01 nginx[1234]: nginx: the configurationfile/etc/nginx/nginx.conf syntax is ok Jan1510:23:45 web01 nginx[1235]: nginx: configurationfile/etc/nginx/nginx.conftestis successful Jan1510:23:45 web01 systemd[1]: Started The nginx HTTP and reverse proxy server.输出字段深度解读字段含义●实心圆绿色active、红色failed、白色inactiveLoaded: loaded单元文件加载状态enabled开机启动disabled不自启vendor preset: disabled软件包默认策略安装时的初始设置Active: active (running)当前运行状态。常见值active (running)、inactive (dead)、failed、activatingsince ... 3 days ago启动时间与运行时长Main PID主进程 PID配合kill -MAINPID优雅停止Tasks/Memory/CGroup进程资源使用情况下半部分最近 10 条日志来自 journald相当于journalctl -u nginx -n 10status退出码0active、1inactive、2有多个匹配 unit、3未找到、4无权限。示例 2启动/重启/重载一个服务# 1. 启动 nginx$sudosystemctl start nginx $sudosystemctl is-active nginx active $echo$?0# 2. 修改配置后重载不中断连接$sudonginx-t# 先测试配置语法nginx: the configurationfile/etc/nginx/nginx.conf syntax is ok nginx: configurationfile/etc/nginx/nginx.conftestis successful $sudosystemctl reload nginx $sudosystemctl is-active nginx active# 3. 完整重启会中断连接$sudosystemctl restart nginx# 4. 设置开机自启 立即启动一步到位$sudosystemctlenable--nownginx Synchronizing state of nginx.service with init system... Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service. Jobfornginx.service finished successfully.# 5. 查看是否开机自启$ systemctl is-enabled nginx enabled示例 3查看所有失败的服务故障排查必备# 列出失败的单元$sudosystemctl--failedUNIT LOAD ACTIVE SUB DESCRIPTION ● nginx.service loaded failed failed The nginx HTTP and reverse proxy server ● mysqld.service loaded failed failed MySQL Server LOADReflects whether the unit definition was properly loaded. ACTIVEThe high-level unit activation state, status inactive or active. SUBThe low-level unit activation state, values depend on unit type.2loadedunitslisted.# 查具体某个失败服务的详情$sudosystemctl status mysqld ● mysqld.service - MySQL Server Loaded: loaded(/usr/lib/systemd/system/mysqld.service;enabled;vendor preset: disabled)Active: failed(Result: exit-code)since Mon2024-01-1514:00:01 CST;2s ago Process:5678ExecStart/usr/sbin/mysqld(codeexited,status1/FAILURE)Main PID:5678(codeexited,status1/FAILURE)Jan1514:00:01 db01 systemd[1]: mysqld.service: Scheduled restart job, restart counter is at3. Jan1514:00:01 db01 systemd[1]: Stopped MySQL Server. Jan1514:00:01 db01 systemd[1]: mysqld.service: Start request repeated too quickly. Jan1514:00:01 db01 systemd[1]: mysqld.service: Failed with resultexit-code.Jan1514:00:01 db01 systemd[1]: Failed to start MySQL Server.# 查看详细日志关键排查点$sudojournalctl-umysqld --no-pager|tail-20Jan1514:00:00 db01 mysqld[5678]:2024-01-15T14:00:00.123456Z0[ERROR][MY-000067][Server]unknown variableinnodb_bug_severityblahJan1514:00:00 db01 mysqld[5678]:2024-01-15T14:00:00.123457Z0[ERROR][MY-010119][Server]Aborting示例 4list-units / list-unit-files 信息查询# 列出所有运行中的服务默认$ systemctl list-units--typeservice--staterunning UNIT LOAD ACTIVE SUB DESCRIPTION auditd.service loaded active running Security Auditing Service crond.service loaded active running Command Scheduler nginx.service loaded active running The nginx HTTP and reverse proxy server redis.service loaded active running Advanced key-value store sshd.service loaded active running OpenBSD Secure Shell server# 列出所有已安装的 unit 文件含未启用的$ systemctl list-unit-files--typeservice|head-10UNIT FILE STATE VENDOR PRESET auditd.service enabled enabled crond.service enabled enabled firewalld.service enabled enabled nginx.service enabled disabled redis.service disabled disabled sshd.service enabled enabled STATE 字段说明 enabled - 开机自启 disabled - 未设置自启 static - 不可以自启只能被其他 unit 依赖 masked - 被屏蔽无法启动 generated - 自动生成的 unit# 查看某个服务的依赖树$ systemctl list-dependencies nginx nginx.service ● ├─system.slice ● └─network.target ● ├─NetworkManager.service ● ├─network-online.target ● └─...# 查看反向依赖谁依赖了 nginx$ systemctl list-dependencies nginx--reverse● └─multi-user.target ● └─graphical.target示例 5修改 unit 文件后重载daemon-reload# 场景修改了 /etc/systemd/system/myapp.service# 1. 重新加载所有 unit 文件$sudosystemctl daemon-reload# 2. 然后再重启服务$sudosystemctl restart myapp# 验证是否生效$ systemctlcatmyapp|head-20# /etc/systemd/system/myapp.service[Unit]DescriptionMy Custom ApplicationAfternetwork.target[Service]ExecStart/usr/bin/python3 /opt/myapp/server.pyRestartalwaysUserappuserWorkingDirectory/opt/myappEnvironmentNODE_ENVproduction[Install]WantedBymulti-user.target重要任何手动修改 unit 文件后必须执行daemon-reload否则 systemd 仍使用内存中的旧配置。示例 6用户级 systemd无需 root# 设置用户的开机自启服务user1000.service 下$ systemctl--userenable--nowmyapp Created symlink /home/alice/.config/systemd/user/myapp.service → /usr/lib/systemd/user/myapp.service.# 列出用户单元$ systemctl--userlist-units UNIT LOAD ACTIVE SUB DESCRIPTION myapp.service loaded active running My App dbus-broker.service loaded active running D-Bus User Message Bus# 适用于开发者的本地服务如 syncthing、jellyfin、podman、tmux 守护进程等⚠️ 注意事项1. 启动失败常见原因配置文件语法错误nginx -t、apachectl configtest先自检端口被占用ss -tlnp | grep :80依赖服务未启动After/Requires的服务SELinux/AppArmor 拒绝audit2why /var/log/audit/audit.logType 字段不正确forking服务忘加PIDFile2.mask与disable的区别disable取消软链仍可手动startmask创建指向/dev/null的软链任何方式都无法启动包括手动。用于彻底禁用顽固服务如sudo systemctl mask firewalld再用unmask恢复3.restartvsreload的选择配置变更优先用reload不停服监听端口、用户、group 等不可重载项必须restart不确定就try-reload-or-restart4. 远程管理默认仅控制本机。如需批量管理多机推荐使用Ansible的service/systemd模块或在/etc/ssh/sshd_config配置AcceptEnv SYSTEMD_REMOTE*后用-H userhost远程 systemctlsystemd v246。5. 脚本中调用# 错误会因分页器挂起systemctl status nginx# 正确禁用分页systemctl status nginx --no-pager# 静默 仅退出码systemctl is-active--quietnginxechorunning||echostopped6. 与传统命令对比兼容层CentOS 7 的service nginx start仍可用它内部就是调用 systemctl但显示会经过一层 wrapper建议新脚本直接用 systemctl。传统 SysVinit 命令systemctl 等价service nginx startsystemctl start nginxservice nginx statussystemctl status nginxchkconfig nginx onsystemctl enable nginxchkconfig --listsystemctl list-unit-files --typeserviceinit 0systemctl poweroffinit 6systemctl rebootrunlevelsystemctl get-default 总结systemctl是现代 Linux 系统管理的瑞士军刀其设计哲学是一切皆 Unit。本节重点核心子命令start / stop / restart / reload / status / enable --now / daemon-reload / list-units / --failed两个最重要的习惯① 修改 unit 文件后daemon-reload② 排错先看status下半部分的日志配合journalctljournalctl -u UNIT查看完整日志、-f实时跟踪、--since 1 hour ago时间过滤一切脚本里加--no-pager避免管道/重定向时卡住掌握systemctljournalctl组合后90% 的服务运维问题都能在终端内完成。 相关命令命令用途journalctl查看 systemd 日志systemd-analyze启动性能分析blame查看各服务启动耗时systemd-cgtop按 cgroup 展示资源使用类似 tophostnamectl查看/设置主机名timedatectl时区与时间管理loginctl用户会话管理localectl区域语言设置busctlD-Bus 调试service传统 SysV 兼容层chkconfig传统自启管理已被 enable 替代
返回列表