systemd服务介绍及systemctl工具使用

redhat从centos7开始,各类服务由systemd接管

Systemd的一些特性:
系统引导时实现服务并行启动;
按需激活进程;
系统状态快照;
基于依赖关系定义服务控制逻辑;

Systemd的兼容性:
向后兼容sysv init脚本:
/etc/init.d/ 兼容此目录下的脚本,可由systemd管控
如/etc/init.d/network start 启动网络后,可由systemctl stop network 关闭


systemd相关配置文件
/usr/lib/systemd/system 存放各类service服务
/lib/systemd/system/ 存放各类service服务
/etc/systemd/system/ 添加开机自启后,服务会被链接到此目录下


systemd核心 unit 单元:
unit由其相关配置文件进行标识、识别和配置;文件中主要包含了系统服务、监听的socket、保存的快照以及其它与init相关的信息。如此目录/lib/systemd/system/ 下的各类service,socket,target等文件
常见的unit单元:
Service unit:文件扩展名为.service,用于定义系统服务;
Target unit:文件扩展为.target,用于模拟实现”运行级别“;
Socket unit:.socket,用于标识进程间通信用到的socket文件;


systemctl常用命令:
systemctl [OPTIONS...] COMMAND [NAME...]
启动:systemctl start NAME.service
  systemctl start --now NAME.service 启动服务同时设置开机自启
停止:systemctl stop NAME.service
  systemctl start --now NAME.service 停止服务同时设置禁止开机自启
重启:systemctl restart NAME.service
运行状态:systemctl status NAME.service
查看所有服务:systemctl list-units -t service -a
设置服务开机自启:systemctl enable NAME.service
禁止服务开机自启:systemctl disable NAME.service
查看某服务是否开机自启:systemctl is-enabled NAME.service
禁止某服务启动和设置开机自启:systemctl mask NAME.service
取消此禁止:systemctl unmask NAME.service


等同于service命令:service NAME.service start|stop|status|restart|reload|force-reload


systemd运行级别:
获取默认运行级别:systemctl get-default
修改默认运行级别:systemctl set-default NAME.target
systemctl set-default multi-user.target 设置运行级别为命令行
systemctl set-default graphical.target 设置运行级别为图形化


service文件内容说明:
一般service文件由三节组成,分别为[Unit],[Service],[Install]
Unlt段的常用选项:
Descrlptlon:描述信息:意义性描述:
After:定义unit的启动次序:表示当前unit应该晚于哪些unilt启动:其功能与Before相反
Requles:依赖到的其它units:强依赖,被依赖的units无法激活时,当前unit即无法激活
Wants:依赖到的其它unlts;弱依赖;
Confulcts:定义uplts间的冲突关系
Service段的常用选项:
Type:用于定义影响ExecStart及相关参数的功能的unlt进程启动类型:
Install段的常用选项:
Alias:
RequlredBy:被哪些units所依赖:
WantedBy:被哪些units所依赖:


注:新创建的unit文件,或者修改了unit文件,需要重载systemd,使新配置生效
systemctl daemon-reload

 

附:一个完整的httpd.service文件

[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/httpd
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful
ExecStop=/bin/kill -WINCH ${MAINPID}
# We want systemd to give httpd some time to finish gracefully, but still want
# it to kill httpd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give
# httpd time to finish.
KillSignal=SIGCONT
PrivateTmp=true

[Install]
WantedBy=multi-user.target

 

posted on 2025-01-07 20:28  赛博狗尾草  阅读(394)  评论(0)    收藏  举报

导航