Search code examples
dockernetwork-programmingrediscontainers

Unable to connect to redis from another docker container


I am running redis-server inside a docker container. It is running on 127.0.0.1 port 6379.

In Container: I am able to connect to the redis-server when within the container and process commands without a problem.

From Host: When I do redis-cli from the host to the container using redis-cli monitor it gives Error: Server closed the connection.

If I just do redis-cli , it gives the prompt;

127.0.0.1:6379> 
127.0.0.1:6379> set www yee
Error: Server closed the connection

This seems that the docker has the right port exposed and the docker port mapping is working. The failure is not at establishing the connection, but the connection gets terminated soon after.

From another container on the same docker (bridge) network:

redis.on('error', function(err) {    
        logger.error('Redis error: ' + err);
    } );

Redis error: Redis connection to 172.18.0.2:6379 failed - connect ECONNREFUSED 172.18.0.2:6379

My redis.conf file has protected-mode no.

The logging is set to debug but there is no information on the log either that shows that a connection was attempted and declined.

The redis client keeps retrying on timeout but every time it gets connection refused. I have tried using both the container name (as hostname) and the container IP address on the docker network and in both cases the result is identical.

docker network create redisnet
docker run --name redis -p 6379:6379 -d --net "redisnet" redis-server
docker run --name apiserver -p 81:8080 --net "redisnet" -d api-server

If I try to ping it from another container on the same net:
docker run -it --rm --net redisnet redis redis-cli -h redis ping
Could not connect to redis at redis:6379: Connection refused

If there are any tips for debugging this would be very helpful;


Solution

  • I fixed this by commenting out the following line in redis.conf.

    # bind 127.0.0.1
    

    When redis is started on a container and attached to a docker network, a new interface is created on that network for redis, and this interface has its own ip address. For instance the docker network can assign addresses in the range 172.18.0.2/24 and the redis container could be assigned 172.18.0.2. Its not always possible to predict which IP address will be assigned to redis, unless one were explicitly assigning the ip address in the docker run command. The only option is to comment the bind in redis.conf, which will allow redis to now listen for requests to 6379 on all interfaces.

    This fixed the problem and I am able to connect to redis from another container.