本文旨在阐明如何在centos 7的系统下,安全安装redis服务。
1,禁止redis开放到外网
2,为redis配置登陆密码
3,以非root用户启动
4,禁用掉危险的命令
下面以在centos7的系统环境下,安装redis 4.0.14为例,
前面步骤按照常规,先下载redis源码包,解压,编译和安装
cd /usr/local/src && wget http://download.redis.io/releases/redis-4.0.14.tar.gz
tar -zxvf redis-4.0.14.tar.gz && cd redis-4.0.14
make && make install
cp redis.conf /etc/
创建一个redis用户,用于运行redis命令
useradd redis
passwd redis
修改redis的配置文件:
#支持后台启动
sed -i "s#daemonize no#daemonize yes#g" /etc/redis.conf
#日志文件存放路径配置
sed -i 's#logfile ""#logfile "/home/redis/redis.log"#g' /etc/redis.conf
#数据文件存放路径
sed -i 's#dir ./#dir /home/redis/#g' /etc/redis.conf
sed -i 's#appendonly no#appendonly yes#g' /etc/redis.conf
#给config命令重命名
echo "rename-command CONFIG CONFIG_xxMnq5ul0c" >> /etc/redis.conf
#禁用掉清空数据库的命令
echo 'rename-command FLUSHDB ""' >> /etc/redis.conf
echo 'rename-command FLUSHALL ""'>> /etc/redis.conf
#为redis配置密码
echo "requirepass password" >> /etc/redis.conf
为redis服务配置service文件:
vim /etc/init.d/redis
#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
### BEGIN INIT INFO
# Provides: redis_6379
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Redis data structure server
# Description: Redis data structure server. See https://redis.io
### END INIT INFO
REDISPORT=6379
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli
PIDFILE=/home/redis/redis_${REDISPORT}.pid
CONF="/etc/redis.conf"
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 -a 'PASSWORD' shutdown
while [ -x /proc/${PID} ]
do
echo "Waiting for Redis to shutdown ..."
sleep 1
done
echo "Redis stopped"
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Please use start,stop or restart as first argument"
;;
esac
然后执行命令:
chmod +x /etc/init.d/redis
chkconfig --add redis
启动的时候,可以使用下面的命令进行启动:
su - redis -c "service redis start"
关闭命令:su -redis -c "service redis stop"
一些不足之处:
1,在service文件中,将密码写在了这个文件里面,因为redis-cli关闭服务的时候,需要使用密码认证。
2,所有的文件都放在了/home/redis/下面。
如果大家有些什么好的改进,请在下方留言,谢谢!!