skip to Main Content

I am trying to do a basic docker container(s) with spring boot and MongoDB and redis. Mongo is just fine but connection can’t be established between redis and spring boot although the configuration looks ok to me.

docker-compose.yml

version: "3.9"
services:
  web:
    build: .
    ports:
      - "1234:1234"
    depends_on:
      - redis
      - db
  db:
    image: mongo
    hostname: mongodb
    ports:
      - "27017:27017"
  redis:
    hostname: redis
    image: redis
    restart: always
    ports:
      - "6379:6379"

Dockerfile:

FROM adoptopenjdk:11
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

Config.java:

@Configuration
@EnableRedisRepositories
public class Config
{

    RedisStandaloneConfiguration standaloneConfiguration() {
        return new RedisStandaloneConfiguration("redis", 6379);
    }

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

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

Problem: All the containers are running after docker compose up. but the connection between spring and redis can’t be established.

java.net.ConnectException: Connection refused (Connection refused)
slot-web-1    |     at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
slot-web-1    |     at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
slot-web-1    |     at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
slot-web-1    |     at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
slot-web-1    |     at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na]

2

Answers


  1. Chosen as BEST ANSWER

    This error may occur if your redis server is starting later than your spring boot. Make sure redis is started first by the following command.

    docker compose down && docker compose up -d redis && sleep 5 && docker compose up --build -d
    

  2. First of all, if your container is on a remote server, you can use telnet on the server where the container is deployed to test whether it can connect to port 6379 of redis. If so, you can check whether the server has open port 6379, or a whitelist.
    Secondly, you can try to connect to the 6379 port of the container redis by telnet on the computer.
    If yes, you can check if the ip, password, username and other information of your redis configuration are correct.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search