0

Im trying to run a spring boot application with redis locally using docker. The app cannot seems to connect with the redis container.

My Dockerfile

FROM java:8
VOLUME /tmp
ADD target/test-*.jar test.jar
RUN bash -c 'touch /test.jar'
EXPOSE 8080
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/test.jar"]

docker-compose.yml

version: '2'
services:
  app:
    build: .
    ports:
      - "8080:8080"
    links:
      - "db:redis"
  db:
    image: "redis:alpine"
    hostname: redis
    ports:
      - "6379:6379"

application properties

spring.redis.host=redis

When the application try to connect to the database it throws

Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool] with root cause
app_1  | 
app_1  | java.net.ConnectException: Connection refused (Connection refused)

Code that i use to connect to db

@Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }

any help would be really appreciated. Thanks

9
  • Does this answer your question? When to use --hostname in docker? Commented Sep 3, 2020 at 20:32
  • What you probably want is an alias for db or just call the container by its service name db. Commented Sep 3, 2020 at 20:35
  • spring.redis.port is set? how do you connect to the redis in your code? Commented Sep 3, 2020 at 20:38
  • @Turing85 Do you mean using links: - "db" instead of links: - "db:redis" ? Commented Sep 3, 2020 at 21:04
  • Yes. Or forego links alltogether since it is deprecated and use depends_on or user-defined networks. Commented Sep 3, 2020 at 21:06

1 Answer 1

0

Change your docker-compose.yml file link in app service to - links: - "db". When making a link between two services, you dont need to add the hostname. The hostname will be used to refer in your code. Which you have done correctly in your applications.properties file.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. I tried that.. but still giving the same exception
"The hostname will be used to refer in your code." - No. The hostname sets the hostname in the container it is specified on (i.e. pinging the hostname from within the container will result in pinging localhost)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.