目录

序言

服务创建

1、服务代码

2、服务配置

服务维护

1、常用操作指令

(1)服务启动

(2)服务停止

(3)服务重启

(4)查看服务状态

(5)服务RELOAD

(6)服务配置修改后重新加载

2、设置开机启动

(1)查看服务开机启动状态

(2)设置开机启动


序言

Linux服务可以在后台运行,操作标准化(start,stop,reload等统一操作,用systemctl进行调控),可开机自动运行,运维人员维护会相对简便,对于一些需要长期稳定运行的程序,则适合把它做成服务的形式。这里以一个定期清理docker镜像的场景为例,说明如何在CentOS7中创建服务并运行。

服务创建

1、服务代码

服务完成这样一个任务,每隔30秒,检查一下docker镜像是否有包含“<none>"版本的镜像(老的版本,可以废弃),如找到则清理该镜像。

同时,将操作日志写入monitor.log文件,以便查看任务所做的操作。

# ! /bin/bash

logfile="/home/test/monitor.log"
pidfile="/home/test/pid"
echo > $logfile
while true
do
	none_num=`docker images | grep "<none>" | grep -v grep | wc -l`
	if [ $none_num -gt 0 ]
	then
		now=`date "+%Y-%m-%d %H:%M:%S"`
		echo "[$now] Found <none> images" >> $logfile
		docker images | grep "<none>" | awk '{print $3}' | xargs docker rmi >> $logfile 2>&1
	else
		now=`date "+%Y-%m-%d %H:%M:%S"`
		echo "[$now]  Not found <none> images"  >> $logfile
	fi
	sleep 30
done

2、服务配置

在/usr/lib/systemd/system目录,创建服务配置文件。这里取名为helloworld服务,看起来更亲切。服务配置文件名为:helloworld.service。

[Unit]
Description=Service hello world
Documention=
After=

[Service]
type=forking
PIDFile=/home/test/pid
ExecStartPre=
ExecStart=/bin/bash -c "nohup /home/test/test.sh &"
EsecReload=/bin/bash -c "echo > /home/test/monitor.log"
ExecStop=/bin/kill -s QUIT $MAINPID

[Install]
WantedBy=multi-user.target

这里说明几个关键参数的含义:

PIDFile: 服务进程的ID文件,可以不填,如果填了,服务程序要生成该PID文件,否则服务将不能启动。

ExecStart:服务启动命令,需要用全路径,这里使用bash启动服务程序脚本,并使用nohup和 &指令让程序在后台运行。

ExecReload:服务执行reload命令时调用的命令。这里设定的操作为,执行reload时,清空监控文件中的内容。

ExecStop: 服务停止命令,使用kill向服务进程发出QUIT指令。$MAINPID指服务进程ID。

 

服务维护

1、常用操作指令

(1)服务启动

systemctl start helloworld

(2)服务停止

systtemctl stop helloworld

(3)服务重启

systemctl restart helloworld

注:相当于stop和stop2个命令的合集,如果服务未启动,则启动;如已启动,则关闭后再启动。

(4)查看服务状态

 systemctl status helloworld

注:可以查看服务运行是否正常。

(5)服务RELOAD

systemctl reload helloworld

注:该命令主要用于数据的刷新,例如清理数据,重新加载数据等,一般不杀掉进程重启。

(6)服务配置修改后重新加载

systemctl deamon-reload

注:在服务配置文件(helloworld.service)修改后,需要执行该命令使配置生效。

2、设置开机启动

(1)查看服务开机启动状态

systemctl list-unit-files | grep helloworld

可以看到,helloworld状态为disabled状态

(2)设置开机启动

chkconfig --level 3 helloworld on

再执行systemctl list-unit-files | grep helloworld命令时,可以发现开机启动状态变为enabled了。

在机器重启后,该服务会自动启动(可以用systemctl status helloworld 命令查看)。

另外相同功能的命令: systemctl enable helloworld。

注意:服务一定要调试好后再设置开机启动,否则,可能会导致系统启动失败。