且构网

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

无法连接到在本地 Docker 容器中运行的 Go GRPC 服务器

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

当您指定要侦听的主机名或 IP 地址(在本例中为解析为 127.0.0.1 的 localhost)时,您的服务器将仅侦听该IP地址.

When you specify a hostname or IP address​ to listen on (in this case localhost which resolves to 127.0.0.1), then your server will only listen on that IP address.

当您在 Docker 容器之外时,在 localhost 上侦听不是问题.如果您的服务器只侦听 127.0.0.1:51672,那么您的客户端可以轻松连接到它,因为连接也是从 127.0.0.1 建立的.

Listening on localhost isn't a problem when you are outside of a Docker container. If your server only listens on 127.0.0.1:51672, then your client can easily connect to it since the connection is also made from 127.0.0.1.

当您在 Docker 容器中运行服务器时,它只会像以前一样侦听 127.0.0.1:51672.127.0.0.1 是本地环回地址,在容器外无法访问.

When you run your server inside a Docker container, it'll only listen on 127.0.0.1:51672 as before. The 127.0.0.1 is a local loopback address and it not accessible outside the container.

当您使用-p 51672:51672"启动 docker 容器时,它会将前往 127.0.0.1:51672 的流量转发到容器的 IP 地址,在我的情况下为 172.17.0.2.

When you fire up the docker container with "-p 51672:51672", it'll forward traffic heading to 127.0.0.1:51672 to the container's IP address, which in my case is 172.17.0.2.

容器在 docker0 网络接口中获取 IP 地址(您可以使用ip addr ls"命令查看)

The container gets an IP addresses within the docker0 network interface (which you can see with the "ip addr ls" command)

因此,当您的流量被转发到 172.17.0.2:51672 上的容器时,那里没有任何监听,连接尝试失败.

So, when your traffic gets forwarded to the container on 172.17.0.2:51672, there's nothing listening there and the connection attempt fails.

修复:

问题在于监听端点:

endpoint := "localhost:51672"

要解决您的问题,请将其更改为

To fix your problem, change it to

endpoint := ":51672"

这将使您的服务器侦听所有容器的 IP 地址.

That'll make your server listen on all it container's IP addresses.

附加信息:

当您在 Docker 容器中公开端口时,Docker 将创建 iptables 规则来执行实际转发.请参阅.您可以查看这些规则与:

When you expose ports in a Docker container, Docker will create iptables rules to do the actual forwarding. See this. You can view these rules with:

iptables -n -L 
iptables -t nat -n -L