本文以redis服务为例,介绍了两种服务自启动的方法service,systemctl使用示例
1.修改redis.conf,允许后台运行
daemonize no 改为 daemonize yes2.使用service命令
1)编写启动shell脚本,命名为redis redis文件代码如下:#!/bin/sh#Configurations injected by install_server below....EXEC=/home/shijingjing/redis-4.0.2/src/redis-server # redis-server的路径CLIEXEC=/home/shijingjing/redis-4.0.2/src/redis-cli # redis-cli的路径PIDFILE=/var/run/redis_6379.pid # redis.conf里有这个参数,将其复制过来CONF="/home/shijingjing/redis-4.0.2/redis.conf" # redis.conf的路径REDISPORT="6379" # 端口################ SysV Init Information# chkconfig: - 58 74# description: redis is the redis daemon.### BEGIN INIT INFO# Provides: redis# Required-Start: $network $local_fs $remote_fs# Required-Stop: $network $local_fs $remote_fs# Default-Start: 2 3 4 5# Default-Stop: 0 1 6# Should-Start: $syslog $named# Should-Stop: $syslog $named# Short-Description: start and stop redis# Description: Redis daemon### END INIT INFOcase "$1" in start) if [ -f $PIDFILE ] then echo "$PIDFILE exists, process is already running or crashed" else echo "Starting Redis server..." $EXEC $CONF fi ;; stop) if [ ! -f $PIDFILE ] then echo "$PIDFILE does not exist, process is not running" else PID=$(cat $PIDFILE) echo "Stopping ..." $CLIEXEC -p $REDISPORT shutdown while [ -x /proc/${PID} ] do echo "Waiting for Redis to shutdown ..." sleep 1 done echo "Redis stopped" fi ;; status) PID=$(cat $PIDFILE) if [ ! -x /proc/${PID} ] then echo 'Redis is not running' else echo "Redis is running ($PID)" fi ;; restart) $0 stop $0 start ;; *) echo "Please use start, stop, restart or status as first argument" ;;esac
将redis文件放入/etc/init.d文件夹中,也可以直接将安装目录下utils/redis_init_script文件拷贝到该目录下
更改文件为可执行
chmod +x redis
2)将执行文件放入,移除开机自启动
update-rc.d redis defaultsupdate-rc.d redis remove
3)手动启动关闭redis
/etc/init.d/redis start/etc/init.d/redis stop/etc/init.d/redis restart
3.使用systemctl命令
1)编写.service文件,redis.service[Unit]Description=RedisAfter=network.target[Service]ExecStart=/usr/bin/redis-server /etc/redis.conf --daemonize noExecStop=/usr/bin/redis-cli -h 127.0.0.1 -p 6355 shutdown[Install]WantedBy=multi-user.target
将redis.service放入/etc/systemd/system文件夹下
2)将服务加入,移除开机自启动
systemctl enable redissystemctl disable redis
3)手动启动关闭redis
systemctl start redissystemctl stop redissystemctl restart redis
4.service和systemctl比较
systemd兼容service,更为的强大 编写服务启动脚本也更简洁,service需要编写完整的shell脚本,systemd只需要配置执行文件,pid文件路径,剩下的交给systemd去做就可以了