在CentOS上保护Redis,核心目标是防止未授权访问、降低被入侵风险。下面按推荐优先级给你一套完整、可落地的方案(适用于生产环境)。
Redis 默认无密码,必须设置。
编辑配置文件:
vim /etc/redis.conf
设置密码:
requirepass your_strong_password
重启 Redis:
systemctl restart redis
登录验证:
redis-cli
AUTH your_strong_password
✅ 这是防止 Redis 未授权访问的第一道防线
bind 127.0.0.1
如果是多服务访问:
bind 127.0.0.1 192.168.1.10
❌ 不要:
bind 0.0.0.0
port 6379
改为:
port 16379
减少被扫描风险。
防止被利用执行系统命令(如 FLUSHALL、CONFIG)。
rename-command FLUSHALL ""
rename-command CONFIG ""
rename-command SHUTDOWN ""
rename-command KEYSD ""
或重命名:
rename-command FLUSHALL "FLUSHALL_abc123"
只允许指定 IP 访问 Redis:
firewall-cmd --permanent --add-rich-rule='
rule family="ipv4"
source address="192.168.1.20"
port protocol="tcp" port="6379" accept'
firewall-cmd --reload
❌ 不要直接开放 6379 到公网
检查 Redis 用户:
ps -ef | grep redis
Redis 默认使用 redis 用户,如不是:
useradd -r -s /sbin/nologin redis
chown -R redis:redis /var/lib/redis
确保 Redis 配置文件中有:
protected-mode yes
并且 不要 开启:
# 禁止
# enable-module-cache yes
# 禁止持久化(如不需要)
save ""
或限制目录权限:
chmod 700 /var/lib/redis
chown redis:redis /var/lib/redis
✅ 最佳实践
应用服务器 → 内网 → Redis(无公网IP)
✅ 如果是云服务器:
| 检查项 | 是否完成 |
|---|---|
| 设置 requirepass | ✅ |
| bind 127.0.0.1 | ✅ |
| 修改默认端口 | ✅ |
| 禁用危险命令 | ✅ |
| 防火墙限制 IP | ✅ |
| 非 root 运行 | ✅ |
| protected-mode yes | ✅ |
redis.conf你可以直接贴出:
redis-cli CONFIG GET *