Linux服务开机自启动使用示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux服务开机自启动使用示例相关的知识,希望对你有一定的参考价值。
本文以redis服务为例,介绍了两种服务自启动的方法service,systemctl使用示例
1.修改redis.conf,允许后台运行
daemonize no 改为 daemonize yes
2.使用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 INFO
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
;;
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 defaults
update-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=redis
[Service]
PIDFile=/var/run/redis.pid
ExecStart=/home/shijingjing/redis-4.0.2/src/redis-server
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
将redis.service放入/etc/systemd/system文件夹下
2)将服务加入,移除开机自启动
systemctl enable redis
systemctl disable redis
3)手动启动关闭redis
systemctl start redis
systemctl stop redis
systemctl restart redis
4.service和systemctl比较
systemd兼容service,更为的强大
编写服务启动脚本也更简洁,service需要编写完整的shell脚本,systemd只需要配置执行文件,pid文件路径,剩下的交给systemd去做就可以了
以上是关于Linux服务开机自启动使用示例的主要内容,如果未能解决你的问题,请参考以下文章