无法从另一个泊坞窗容器连接到redis

时间:2018-05-28 05:59:52

标签: docker networking redis containers

我在docker容器中运行redis-server。它在127.0.0.1端口6379上运行。

在容器中  我可以在容器和处理命令中连接到redis-server而没有问题。

来自主持人: 当我使用redis-cli监视器从主机到容器执行redis-cli时,它会给出 错误:服务器已关闭连接。

如果我只是做127.0.0.1:6379> 127.0.0.1:6379> set www yee Error: Server closed the connection ,它会给出提示;

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

这似乎是docker有正确的端口暴露,并且docker端口映射正在工作。失败不是建立连接,但连接很快就会终止。

来自同一泊坞(网络)网络上的另一个容器:

redis.conf

我的protected-mode no文件有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

日志记录设置为调试,但日志中没有任何信息显示已尝试和拒绝连接。

redis客户端在超时时继续重试,但每次连接都被拒绝。我尝试在docker网络上同时使用容器名称(作为主机名)和容器IP地址,在这两种情况下结果都是相同的。

l = [5, 2, 2, 1, 4, 5, 4, 6, 6, 5, 5, 3, 3, 2, 1, 3, 5, 3, 5, 2, 4, 4, 2, 3, 3, 2, 6, 2, 3, 6, 3, 6, 1, 6]

6_finder(l)
> [26, 33]

如果有任何调试提示,这将非常有用;

4 个答案:

答案 0 :(得分:5)

要从主机到容器进行通话,您需要在主机上发布端口。例如。 docker run -p 6379:6379 redis。没有必要暴露端口。这将使该服务可用于网络上的任何内容。您可以通过指定要监听的接口来限制它,例如:docker run -p 127.0.0.1:6379:6379 -d redis

要在容器之间进行通信,它们需要位于同一用户创建的docker网络上。 e.g:

docker network create my_app
docker run --net my_app -d --name redis redis

然后,您就可以将其他容器连接到同一网络并与“redis:6379”进行通信。 e.g:

$ docker run -it --rm --net my_app redis redis-cli -h redis ping
PONG

答案 1 :(得分:3)

创建容器时,使用-p选项将redis容器端口映射到主机端口。示例:

sudo docker run  -p 6379:6379 --name containername imageId

然后,您可以访问在主机上容器内运行的redis。

答案 2 :(得分:3)

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.

答案 3 :(得分:1)

虽然已建立连接,但我无法 ping 通 redis-cli

我已通过将 bind 127.0.0.1 中的 bind 0.0.0.0 修改为 redis.conf 解决了这个问题。

相关问题