简体   繁体   中英

Spring Boot Redis getting connection refused exception when using Redis

I have a small application where use I use redis for cache and Spring Boot. Application runs successfully in local but when I try to dockerize it, I'm getting connection refuse exception.

It's my docker-compose.yml file:

version: '3.5'

services:
  my-application:
    image: my-application:latest
    container_name: my-application
    ports:
      - 8080:8080
    hostname: my-application

  redis:
    image: redis
    command: [ "redis-server", "--protected-mode", "no" ]
    volumes:
      - ./data:/data
    ports:
      - 6379:6379   

Dockerfile:

FROM openjdk:7

VOLUME /tmp

ADD my-application-0.0.1.jar my-application-0.0.1.jar

EXPOSE 8080

ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "my-application-0.0.1.jar"]

When I check docker console, I saw that redis starts in standalone mode

What I'm missing ?

Thanks

You have to set:

server.address=0.0.0.0

in your application.properties . If your application is listen on 127.0.0.1 in the container, you won't be able to reach it from your host.

You need to change the redis host to the name of the redis configuration in the docker compose file, in this case - redis

It can be configured by two ways:

  • changing property file spring.redis.host=redis
  • setting host in manual config (redis or jedis) redisStandaloneConfiguration.setHostName("redis");

Also, in my case, I did not use volume in my docker files, so to use the new jar file you need to do all 3 steps of launching docker compose ( apart from clean build in gradle or clean install in maven ):

  • docker-compose down
  • docker-compose build
  • docker-compose up

I hope this is useful to someone! :)

I had the same issue and fixed with (docker-compose.yml)

 cache:
    image: redis
    ...
    ports:
      - 6379:6379  

then in application.properties spring.redis.host=cache

and eventually

@Value("${spring.redis.host}")
String redisHost
...
redisStandaloneConfiguration.setHostName(redisHost);

I think, in docker network, service name with same name of image is causing issues and ending with docker not being able to create connections to redis host.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM