MacBook使用docker方式部署Redis踩坑经历

2023-07-16
预计阅读时间:1分钟

问题:docker宿主机上SpringBoot项目连接docker中的Redis被拒绝

org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; 
nested exception is org.springframework.data.redis.connection.PoolException: Could not get a resource from the pool;
nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 127.0.0.1:6379
	at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.translateException(LettuceConnectionFactory.java:1553)
	at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.getConnection(LettuceConnectionFactory.java:1461)
 
Caused by: org.springframework.data.redis.connection.PoolException: Could not get a resource from the pool; 
nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 127.0.0.1:6379
	at org.springframework.data.redis.connection.lettuce.LettucePoolingConnectionProvider.getConnection(LettucePoolingConnectionProvider.java:109)
	at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.getConnection(LettuceConnectionFactory.java:1459)
	... 78 more
Caused by: io.lettuce.core.RedisConnectionException: Unable to connect to 127.0.0.1:6379
	at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:78)
 
Caused by: io.lettuce.core.RedisConnectionException: Connection closed prematurely
	at io.lettuce.core.protocol.RedisHandshakeHandler.channelInactive(RedisHandshakeHandler.java:86)

思路:停止原有进程,删除容器,宿主机写好配置文件后与容器进行映射,镜像第一次启动时使用映射的配置文件进行启动

redis官方配置文件模板下载地址

在redis对应版本的配置文件中修改下面几项:

# 解除本地连接限制
# bind 127.0.0.1
# 默认yes,解除保护模式,不限制为本地访问
protected-mode no
# 默认no,使用docker启动redis无需处理
daemonize no
# 设置密码
requirpass 123456
# 持久化(可选,容器启动命令已经附带该配置项)
appendonly yes

redis镜像启动命令

docker run --restart=always -p 6379:6379 --name redis -v /Users/defchan/Documents/redis/conf/redis.conf:/etc/redis/redis.conf  -v /Users/defchan/Documents/redis/data:/data -d redis redis-server /etc/redis/redis.conf --appendonly yes

至此,宿主机上的SpringBoot项目成功连接Redis