无法连接远程Ubuntu服务器上的Redis服务(Rails环境)
解决远程Ubuntu Redis连接认证错误问题
问题根源
你当前的代码存在两个关键错误:
- Redis连接URL里错误填入了Ubuntu服务器的账号密码,而非Redis自身的认证信息(用户名/密码)
- URL已包含认证参数的情况下,重复调用
redis.auth()导致认证冲突
正确的连接写法
写法一:使用URL格式(推荐)
如果你的Redis版本支持用户名(Redis 6.0+):
redis = Redis.new(url: "redis://<Redis用户名>:<Redis密码>@<服务器IP>:6379/1") # 无需再调用redis.auth()
如果Redis仅设置了密码(无用户名,常见于旧版本):
redis = Redis.new(url: "redis://:<Redis密码>@<服务器IP>:6379/1")
写法二:分开传递参数
这种方式更直观,避免URL格式混淆:
redis = Redis.new( host: "<服务器IP>", port: 6379, db: 1, username: "<Redis用户名>", # 无用户名则省略此参数 password: "<Redis密码>" )
额外排查步骤
- 检查Redis配置文件(通常为
/etc/redis/redis.conf):- 确保
bind设置为0.0.0.0(允许所有IP访问)或你的客户端IP - 确认
requirepass(全局密码)或user <用户名> on <密码> ~* +@all(用户认证)配置正确
- 确保
- 检查Ubuntu防火墙:执行
sudo ufw allow 6379开放Redis端口 - 先用
redis-cli测试连接:# 带密码直接连接 redis-cli -h <服务器IP> -p 6379 -a <Redis密码> # 或者先连接再认证 redis-cli -h <服务器IP> -p 6379 AUTH <Redis密码> # 若有用户名则用 AUTH <用户名> <密码>
内容的提问来源于stack exchange,提问作者Sachin Singh
相关产品推荐
相关产品推荐

