从 docker 容器到 kubernetes pod 的端口发布是如何工作的?

How does port publishing from a docker container to a kubernetes pod work?

在学习教程时 Get Started, Part 3: Deploying to Kubernetes 我无意中发现了清单文件部署定义中的 Pod 模板。没有指定端口,无论是在 pod 还是在容器部分。

这让我想到了最初的问题:从 docker 容器到 pod 的端口发布是如何工作的?

下面的引用听起来像是 kubernetes 在启动后深入了解 运行 容器,并从侦听 0.0.0.0:PORT 的服务获取端口并将其映射到 pod 环境中的相同端口(网络命名空间)。

Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network. Source

如果我的假设朝着正确的方向发展,这对 pods 具有多个容器意味着什么? kubernetes 是否只允许内部服务侦听不同端口的容器?或者是否可以将容器内部端口映射到 pod 环境(网络命名空间)中的不同端口?

根据以下引述,我假设从容器到 pod 的端口映射是不可能的。 实际上,在具有相同端口的两个容器中指定两个服务并没有太大意义,只是通过紧随其后的映射更改它们。

Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Source


更新 2019-10-15

如以下引用所述,docker 容器默认不会向外界发布任何端口。

By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container’s network, use the --publish or -p flag. Source

这意味着 kubernetes 必须以某种方式在 pod 中配置 docker 容器 运行,以便将容器的端口发布到 pod。

关于下面的引用,kubernetes 是否可以通过使用 --network host 配置来运行 docker 容器?假设 pod 是 kubernetes 中的 docker 主机。

If you use the host network mode for a container, that container’s network stack is not isolated from the Docker host [...] For instance, if you run a container which binds to port 80 and you use host networking, the container’s application is available on port 80 on the host’s IP address. Source

pod 中的容器 运行 类似于连接到网络的节点上的进程 运行。 Pod 获得一个网络地址,所有容器共享同一个网络地址。他们可以使用 localhost.

相互交谈

pod 中的容器 运行 可以侦听该地址上的任何端口。如果一个 pod 中有多个容器运行,它们不能绑定到同一个端口,只有其中一个可以。请注意,没有关于发布这些端口的要求。容器可以侦听任何端口,如果客户端连接到 pod 的该端口,流量将被传送到它。

因此,从容器到 pod 的端口映射是不可能的。

containers/pods暴露的端口主要是信息性的,工具使用它们来创建资源。