且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从主机连接到在Docker容器中运行的Redis

更新时间:2023-10-05 11:16:58

问题是绑定问题,您应该设置以下内容:

 绑定0.0.0.0 

此在具有一个接口( eth0 )和环回的容器化环境中,将设置 redis 绑定到所有可用接口( lo )redis将绑定到以上两个。您应该考虑通过 config文件中的其他指令或使用诸如 firewalls 之类的外部工具来添加安全措施。因为使用这种方法,每个人都可以连接到您的 redis 服务器。



默认设置为绑定127.0.0.1 ,此设置将导致 redis 仅在回送接口上侦听,并且只能从容器内部访问。 (出于安全考虑)



要使用自定义配置文件运行Redis:

  sudo docker run -d --name redis-test -p 6379:6379 -v /path/to/redisconf/redis.conf:/redis.conf redis redis-server /redis.conf 

现在在安装了 redis-tools 的Docker主机上进行验证:

  redis-cli 
127.0.0.1:6379>
127.0.0.1:6379>设置farhad喜欢:***
OK
127.0.0.1:6379>得到远方
likes:***
127.0.0.1:6379>

您还可以将其连接到 redis 容器通过以下方式从外部主机获取:

  redis-cli -h'dockerhost的IP地址-运行-redis-container' 


I see lots of people struggling with this, sort of feel like maybe there is a bug in the redis container image, and others seem to be chasing a similar problem.

I'm using the standard redis image on DockerHub. (https://github.com/dockerfile/redis)

running it like this:

docker run -it -p 6379:6379 redis bash

Once I'm in I can start the server, and do a redis ping from the container image.

Unfortunately, I cannot connect to the redis container from my host.

I have tried setting, such as below.

bind 127.0.0.1

and removed the bind from the configuration

and tried turn off protected mode

protected-mode no

I know it is reading the configuration file, since I changed ports just to test, and I was able to do that.

I'm running Windows 10, so maybe it is a windows networking issue. I never have a problem with docker normally. I'm puzzled

The problem is with your bind, You should set the following:

bind 0.0.0.0

This will set redis to bind to all interfaces available, in a containerized environment with one interface, (eth0) and a loopback (lo) redis will bind to both of the above. You should consider adding security measures via other directives in config file or using external tools like firewalls. because with this approach everyone can connect to your redis server.

The default setting is bind 127.0.0.1 and this setting will cause redis to only listen on loopback interface, and it will be only accessible from inside the container. (for security)

To run redis with custom configuration file:

sudo docker run -d --name redis-test -p 6379:6379  -v /path/to/redisconf/redis.conf:/redis.conf redis redis-server /redis.conf

Now to verify on docker host with redis-tools installed:

redis-cli                           
127.0.0.1:6379> 
127.0.0.1:6379> set farhad likes:***
OK
127.0.0.1:6379> get farhad
"likes:***"
127.0.0.1:6379> 

You can also connnect to your redis container from an external host via:

redis-cli -h 'IP-address-of-dockerhost-running-redis-container'