systemd定义service

简介

systemd是linux上面启动的第一个进程,pid=1,作用是管理用户服务进程。
systemd的特点是可以并行启动服务进程,配置服务进程开机自启动,启动顺序和依赖关系等。

常用命令

下面用sshd服务进程管理演示

systemctl start sshd.service  #启动sshd服务
systemctl status sshd.service  #查看sshd服务状态
    #Loaded行可以看到sshd服务的定义文件 /usr/lib/systemd/system/sshd.service
systemctl stop sshd.service    #停止sshd服务
systemctl enable sshd.service  #设置服务开机自动启动
systemctl disable sshd.service  #关闭服务开机自启动

journalctl  -u sshd   #查看sshd.service的日志
journalctl -u -f sshd  #查看sshd.service的实时日志,和tail -f类似

配置服务

服务的配置文件放在/usr/lib/systemd/system下面,下面是我参考sshd.service文件配置的nginx.service

[Unit]
Description=Nginx server daemon
After=network-online.target
Wants=network-online.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/usr/local/nginx/sbin/nginx -s reload

[Install]
WantedBy=multi-user.target

配置项解释:
每个配置项的解释参考https://www.freedesktop.org/software/systemd/man/systemd.directives.html

配置项 意义
Description 对服务进程的描述,通过systemctl status nginx.service可以看到这段描述
After man systemd.unit可以看到After的作用,此处设置nginx服务需要在
network-online.target启动好了再执行启动
Wants 启动nginx.service的时候会检查network-online.target是否启动了,如果
network-online.target没有启动,那么就会同时执行启动network-onilne.target和nginx.service,network-online.target启动失败也不会影响nginx.service的启动状态
Requires 与Wants相似,但是network-online.target启动失败会导致nginx.service的启动状态是失败
Type forking表示ExecStart配置的启动命令会调用fork(),父进程会在子进程启动好之后退出,父进程正常退出则systemd认为服务启动成功,建议同时配置PIDFile;
oneshot表示执行一次后就退出,适合一次性任务;可以有多个ExecStart,顺序执行,任意一个失败都会导致状态是失败;
exec表示主程序的二进制文件加载执行就认为服务启动成功,适合那种主程序会一直执行,不会立即退出返回的场景;
如果type配置不对,则可能影响systemd对服务状态的判断,systemctl status返回的状态不是预期的。
WantedBy target表示一个启动阶段,每个阶段包含了几个service;systemctl list-dependencies可以查看各个target包含哪些service
ExecStart 执行systemctl start nginx.service时执行的命令
ExecStop 执行systemctl stop nginx.service时执行的命令
ExecReload 执行systemctl enable nginx.service时执行的命令

实践

rc.local

有时候生产环境需要加开机执行某些任务,为了简单都是直接加在/etc/rc.local里面,但是mount -t nfs ip:/path /pathlocal有时候会失败,查看/var/log/messages可以看到 SIOCADDRT: Network is unreachable的报错,猜想应该是网络没有启动好。rc.local的执行实际是通过rc-local.service执行的,rc-local.service文件的确是只配置了After=network.target,所以可以改为After=network-online.target和Wants=network-online.target即可。

vmstat监控

自己创建一个服务,使用vmstat记录系统的状态

#配置文件/usr/lib/systemd/system/mvmstat.service
[Unit]
Description=use vmstat to monitor system
After=network.target

[Service]
Type=exec
ExecStart=/usr/bin/vmstat -w -t 1
StandardOutput=append:/home/monitor/vmstat.log

[Install]
WantedBy=multi-user.target

#shell
systemctl  daemon-reload
systemctl start monitor.service
systemctl status monitor.service
systemctl enable monitor.service

这里将日志打到/home/monitor/vmstat.log,在我的logrotate文章里面有如何配置自动将日志按天切割。

posted @ 2023-05-29 10:35  董少奇  阅读(70)  评论(0)    收藏  举报