Home > Software design >  Connect to Redis using java code if there is docker compose of Redis and Redis Commander
Connect to Redis using java code if there is docker compose of Redis and Redis Commander

Time:11-01

I am trying to connect to Redis using below Java code with Jedis library but connection is failng can someonen please help on this ?.

Jedis jedis = new Jedis("localhost");
String pingResponse = jedis.ping();
System.out.println("ping should return pong"   pingResponse);

and this is my docker-compose file

version: '3'
services:
  redis:
    container_name: redis
    hostname: redis
    image: redis

  redis-commander:
    container_name: redis-commander
    hostname: redis-commander
    image: rediscommander/redis-commander:latest
    restart: always
    environment:
    - REDIS_HOSTS=local:redis:6379
    ports:
    - "8082:8081"

below is the exception I am getting :

Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host redis:6379
    at redis.clients.jedis.Connection.connect(Connection.java:204)
    at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:100)
    at redis.clients.jedis.Connection.sendCommand(Connection.java:125)
    at redis.clients.jedis.Connection.sendCommand(Connection.java:120)
    at redis.clients.jedis.BinaryClient.ping(BinaryClient.java:113)
    at redis.clients.jedis.BinaryJedis.ping(BinaryJedis.java:188)
    at com.altimetrik.demo.bean.Sample.main(Sample.java:23)

CodePudding user response:

i think your Redis container does not expose ports outside for connection, only the commander exposes 8002. (try connecting to localhost:8002). docker compose creates a default "bridge" network so the containers can talk between themselves, but not outside unless you expose ports. the commander can connect to REDIS since they are on the same network.

  • Related