k8s中許多關於port即端口的定義,端口在網絡協議中是7層的概念也就是區分業務的編號。k8s的定義中也有很多關於端口的配置,下面就常見的幾種加以說明。
環境說明
- node主機IP: 172.10.220.201
containers定義中的containerPort
containerPort是容器需要暴露的端口,一般是容器主進程的監聽端口。例如下面,iperf進程一般監聽的是5201端口,所以該容器需要暴露5201端口。
containers:
- name: iperf
args: ['-s']
ports:
- containerPort: 5201
image: 192.168.1.2:1234/iperf:1.0
service中的端口定義
舉一個nodeIP的Service的例子:
apiVersion: v1
kind: Service
metadata:
name: busybox-service
namespace: net
spec:
type: NodePort
selector:
app: busybox
ports:
# By default and for convenience, the `targetPort` is set to the same value as the `port` field.
- port: 80
targetPort: 80
# Optional field
# By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
nodePort: 30007
#創建出來的service如下
kubectl get svc -o wide --all-namespaces
NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
default busybox-service NodePort 10.0.0.155 <none> 80:30007/TCP 15m app=busybox
現就port、targetport和nodePort說明如下:
- port: 是service暴露在cluster ip上的端口,
:port 是提供給集群內部客戶訪問service的入口。也就是說可以在集群內部用10.0.0.155:80端口訪問容器提供的服務; - nodePort: 是kubernetes提供給集群外部客戶訪問service入口的一種方式,
:nodePort 是提供給集群外部客戶訪問service的入口。也就是說集群外部的客戶可以通過172.10.220.201:3007訪問pod提供的服務; - targetPort: 就pod上的真正提供服務的端口,最后的流量都會導到這里來,進入容器內部。