You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Compose下Spring Boot连接Redis(localhost:6379)被拒绝问题

Spring Boot容器无法连接Docker Compose中Redis服务器的解决方法

1. 修复配置属性名不匹配问题

你的Spring Boot配置文件中使用的是spring.data.redis.host,但自定义RedisConfig类里注入的是spring.redis.host,两者属性名不一致,导致应用读取不到Docker Compose中设置的REDIS_HOST环境变量,默认使用了容器内的127.0.0.1(无法指向Redis容器)。

解决方式二选一:

  • 修改配置文件为:
    spring.redis.host= ${REDIS_HOST:127.0.0.1}
    spring.redis.port= 6379
    
  • 或者修改RedisConfig中的注入属性:
    @Value("${spring.data.redis.host}")
    private String host;
    @Value("${spring.data.redis.port}")
    private Integer port;
    

2. 修正Docker Compose的服务依赖配置

你把服务启动依赖写在了environment块中,这是错误的语法,应该移到depends_on块内,确保Redis服务完全就绪后再启动Spring Boot应用:

修改后的iam-service配置:

iam-service:
  build:
    context: ./iam-service
  container_name: iam-service
  ports:
    - "8082:8082"
  environment:
    IAM_INTERNAL: http://iam-service:8082
    STORAGE_INTERNAL: http://storage-service:8083
    REDIS_HOST: redis-server
    POSTGRES_URL: jdbc:postgresql://my_postgres:5432/iam_db
  depends_on:
    postgres:
      condition: service_healthy
    keycloak:
      condition: service_started
    redis-server:
      condition: service_healthy  # 用健康检查就绪替代单纯启动,更可靠
  networks:
    - royalnet

3. 验证容器间网络连通性

进入Spring Boot容器,直接测试与Redis容器的连通性:

# 进入iam-service容器
docker exec -it iam-service bash

# 测试Redis容器域名是否可达
ping redis-server

# 用redis-cli尝试连接
redis-cli -h redis-server ping

如果无法连通,执行docker network inspect royalnet检查两个容器是否都加入了royalnet网络。

4. 确认Redis配置文件是否生效

进入Redis容器验证配置是否正确加载:

docker exec -it redis-server redis-cli config get bind
docker exec -it redis-server redis-cli config get protected-mode

若返回值不是0.0.0.0和no,说明配置文件挂载路径错误。Redis官方镜像默认配置路径为/etc/redis/redis.conf,可修改Docker Compose中的挂载配置:

redis-server:
  # 其他配置不变
  command: redis-server /etc/redis/redis.conf
  volumes:
    - redis_data:/data
    - ./redis.conf:/etc/redis/redis.conf

内容的提问来源于stack exchange,提问作者RoyalPie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:19:56