您可以选择定义一个没有Pod选择器的服务。然后通过手动添加Endpoint对象将该服务映射到其运行的网络地址和端口。
以下是示例:
创建两个类型为nginx的Pod
$ kubectl get all -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod/nginx-one 1/1 Running 0 4m56s 192.168.58.199 k8s-node02 <none> <none>
pod/nginx-two 1/1 Running 0 4m50s 192.168.85.193 k8s-node01 <none> <none>
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 29m <none>
使用以下yamls创建两个服务,注意下面的yaml中没有使用Pod选择器字段
service1.yaml:
apiVersion: v1
kind: Service
metadata:
name: nginx-one-service
spec:
ports:
- protocol: TCP
port: 80
service2.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-two-service
spec:
ports:
- protocol: TCP
port: 80
$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 32m
nginx-one-service ClusterIP 10.102.230.78 <none> 80/TCP 7m16s
nginx-two-service ClusterIP 10.98.86.67 <none> 80/TCP 6m56s
描述服务,没有映射任何终点,因为我们没有给出选择器。
ubuntu@k8s-master:~$ kubectl describe service nginx-one-service
Name: nginx-one-service
Namespace: default
Labels: <none>
Annotations: <none>
Selector: <none>
Type: ClusterIP
IP: 10.102.230.78
Port: <unset> 80/TCP
TargetPort: 80/TCP
Endpoints: <none>
Session Affinity: None
Events: <none>
ubuntu@k8s-master:~$ kubectl describe service nginx-two-service
Name: nginx-two-service
Namespace: default
Labels: <none>
Annotations: <none>
Selector: <none>
Type: ClusterIP
IP: 10.98.86.67
Port: <unset> 80/TCP
TargetPort: 80/TCP
Endpoints: <none>
Session Affinity: None
Events: <none>
现在你可以选择使用以下的yamls手动映射终点。
endpoint1.yaml
apiVersion: v1
kind: Endpoints
metadata:
name: nginx-one-service
subsets:
- addresses:
- ip: 192.168.85.193
ports:
- port: 80
endpoint2.yaml
apiVersion: v1
kind: Endpoints
metadata:
name: nginx-two-service
subsets:
- addresses:
- ip: 192.168.85.193
ports:
- port: 80
现在可以在创建时获取端点
$ kubectl get endpoints
NAME ENDPOINTS AGE
kubernetes 131.160.188.46:6443 35m
nginx-one-service 192.168.58.199:80 5m30s
nginx-two-service 192.168.85.193:80 4m59s
并列出应该将服务和终端点映射为以下内容:
ubuntu@k8s-master:~$ kubectl describe service nginx-one-service
Name: nginx-one-service
Namespace: default
Labels: <none>
Annotations: <none>
Selector: <none>
Type: ClusterIP
IP: 10.102.230.78
Port: <unset> 80/TCP
TargetPort: 80/TCP
Endpoints: 192.168.58.199:80
Session Affinity: None
Events: <none>
ubuntu@k8s-master:~$ kubectl describe service nginx-two-service
Name: nginx-two-service
Namespace: default
Labels: <none>
Annotations: <none>
Selector: <none>
Type: ClusterIP
IP: 10.98.86.67
Port: <unset> 80/TCP
TargetPort: 80/TCP
Endpoints: 192.168.85.193:80
Session Affinity: None
Events: <none>