linux 设置服务开机自启动

前言

由于机房断电,导致服务关闭,在运维人员匆忙的情况下,可能就只重启了机器,很容易就忽视了里面的服务,而对于比较重要的服务,是会影响用户使用的,比如数据库服务等。那么为了杜绝这类事情的发生,我们就需要设置服务为开机自启动,当机房断电,机器重启时,在不需要运维人员的干预下,核心重要的服务能够自动启动,接下来将详细说明在linux centos环境下如何设置开机自启动。

设置自启动

在Linux操作系统中,如果要将某个程序添加到开机启动项时。你可以将其放到/etc/init.d目录,并使用chkconfig命令将其配置为系统服务,然后使用service命令控制脚本(例如:service redis start);或者简单的将启动命令添加到rc.local开机启动文件中。下面以redis服务设置开机自启动为例进行说明。

方式1:直接将启动命令配置到/etc/rc.d/rc.local文件中

/usr/local/redis-3.2.5/src/redis-server /usr/local/redis-3.2.5/redis.conf &

image

方式2:使用chkconfig命令设置
vim /etc/init.d/redis

# chkconfig: 2345 10 90
# description: Start and Stop redis

PATH=/usr/local/bin:/sbin:/usr/bin:/bin

#以下变量值视实际环境而定
REDISPORT=6379
EXEC=/usr/local/redis-3.2.5/src/redis-server
REDIS_CLI=/usr/local/redis-3.2.5/src/redis-cli

PIDFILE=/usr/local/redis-3.2.5/redis.pid
CONF="/usr/local/redis-3.2.5/redis.conf"

case "$1" in
start)
if [ -f $PIDFILE ]
then
echo "$PIDFILE exists, process is already running or crashed."
else
echo "Starting Redis server..."
$EXEC $CONF
fi
if [ "$?"="0" ]
then
echo "Redis is running..."
fi
;;
stop)
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE exists, process is not running."
else
PID=$(cat $PIDFILE)
echo "Stopping Redis Server..."
$REDIS_CLI -p $REDISPORT SHUTDOWN
while [ -x $PIDFILE ]
do
echo "Waiting for Redis to shutdown..."
sleep 1
done
echo "Redis stopped"
fi
;;
restart)
${0} stop
${0} start
;;
*)
echo "Usage: /etc/init.d/redis {start|stop|restart}" >&2
exit 1
esac

设置脚本执行权限:

chmod +x /etc/init.d/redis

开机自启动设置:

# 开启服务自启动
chkconfig redis on

chkconfig命令使用

chkconfig命令用于配置哪些服务需要自启动的。

# 查看所有自启动系统服务
chkconfig --list

# 添加xxx为自启动系统服务
chkconfig --add xxx

# 删除xxx自启动系统服务
chkconfig --del xxx

# 开启xxx在2、3、4、5运行级别上是自启动系统服务,如果没有add则自动添加服务
chkconfig xxx on

# 关闭xxx自启动系统服务
chkconfig xxx off

#设置xxx服务在运行级别为3、4、5时,都是开启的状态
chkconfig --level xxx 345 on

image

参考链接

  1. https://itbilu.com/linux/man/NJGgaE9Ix.html