Kubernets 网络示例


这里以 Nginx 为例,介绍几种常见的网络模型。

HostNetwork

apiVersion: v1
kind: Pod
metadata:
  name: nginx-hostnetwork
spec:
  hostNetwork: true
  containers:
  - name: nginx-hostnetwork
    image: nginx:latest
    imagePullPolicy: Never
----- 创建主机网络
kubectl create -f hostnetwork.yaml
----- 查看对应的IP地址,直接通过curl访问即可
kubectl get pod --all-namespaces -o=wide
----- 清理无需Pod
kubectl delete pods nginx-hostnetwork

在 Kind 测试集群中也可以直接访问。

HostPort

apiVersion: v1
kind: Pod
metadata:
  name: nginx-hostport
spec:
  containers:
  - name: nginx-hostport
    image: nginx:latest
    imagePullPolicy: Never
    ports:
    - containerPort: 80
      hostPort: 8088
kubectl create -f hostport.yaml
kubectl get pod --all-namespaces -o=wide
kubectl delete pods nginx-hostport

ClusterIP

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  selector:
    matchLabels:
      run: nginx
  replicas: 2
  template:
    metadata:
      labels:
        run: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        imagePullPolicy: Never
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:         
  name: nginx-svc
spec:
  selector:
    run: nginx
  ports:
  - protocol: TCP
    port: 8080
    targetPort: 80

NodePort

其中的 Deployment 保持不变,仅需要修改 Service 配置。

apiVersion: v1
kind: Service
metadata:         
  name: nginx-svc
spec:
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 8080
    targetPort: 80
    nodePort: 30080
  type: NodePort