为什么要通过网络名称空间连接两个docker容器,而不仅仅通过一个网络连接?
据我所知,唯一的区别是你可以使用localhost调用另一个容器。我没有看到任何必要的用例。
有任何人对此有经验吗?
我能想到的一个原因是使用容器中没有的工具或命令。下面这个例子直接来自docker run
docs:
NETWORK: CONTAINER
运行Redis容器的示例,其中Redis绑定到
localhost
,然后运行redis-cli
命令并通过localhost
接口连接到Redis服务器。$ docker run -d --name redis example/redis --bind 127.0.0.1 $ # use the redis container's network stack to access localhost $ docker run --rm -it --network container:redis example/redis-cli -h 127.0.0.1
以类似的方式,可以使用此技术来调试容器。例如,如果您的容器没有tcpdump
,您可以创建一个包含它的图像:
docker build -t tcpdump - <<EOF
FROM ubuntu
RUN apt-get update && apt-get install -y tcpdump
CMD tcpdump -i eth0
EOF
和run
一个容器来调试你的应用程序:
docker run --rm --net=container:my-app tcpdump
如果你的问题更多是关于Kubernetes的话,一些有趣的链接是: