温馨提示×

centos如何设置redis密码

小樊
38
2026-07-08 07:46:09
栏目: 云计算

CentOS 上给 Redis 设置密码,常见有两种方式:临时设置(重启失效)永久设置(推荐)。下面按步骤说明。


一、永久设置 Redis 密码(推荐)

1. 编辑 Redis 配置文件

Redis 的配置文件一般在:

/etc/redis.conf

或(某些版本):

/etc/redis/redis.conf

使用 vim 打开:

vim /etc/redis.conf

2. 找到并修改 requirepass

搜索:

# requirepass foobared

去掉注释并修改密码,例如:

requirepass MyStrongPassword123

⚠️ 注意:

  • 不要保留 #
  • 密码不要使用弱密码

3. 重启 Redis 服务

CentOS 7 / 8 使用 systemd:

systemctl restart redis

或:

systemctl restart redis-server

4. 验证密码是否生效

redis-cli
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.

输入密码:

127.0.0.1:6379> AUTH MyStrongPassword123
OK
127.0.0.1:6379> ping
PONG

✅ 设置成功


二、临时设置密码(重启后失效)

适用于测试环境:

redis-cli
CONFIG SET requirepass MyStrongPassword123

查看:

CONFIG GET requirepass

⚠️ 重启 Redis 后密码会丢失


三、Redis 授权后常用操作

登录时直接带密码

redis-cli -a MyStrongPassword123

(会有警告,不影响使用)

先登录再认证

redis-cli
AUTH MyStrongPassword123

四、安全建议(非常重要)

1. 禁止外网访问

bind 127.0.0.1

2. 修改默认端口

port 6379

改为其他端口,如:

port 16379

3. 启用保护模式

protected-mode yes

4. 不要暴露 Redis 到公网

Redis 不适合直接暴露在公网,建议:

  • 使用防火墙
  • 或只通过内网访问

五、常见问题

❓ 设置密码后无法启动

检查:

  • 配置文件语法错误
  • 是否忘记重启 Redis

❓ 客户端连不上

确认:

  • 密码是否正确
  • 是否修改了端口
  • 防火墙是否放行

如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8)
  • Redis 安装方式(yum / 编译)

我可以给你更精确的配置示例 ✅

0