K8S编排 之 Service

本文的主线 引入 => 使用 => 特性

引入

  • Pod解决了容器的”超亲密关系”设计

  • Deployment解决了Pod水平扩展的问题

  • Service解决了Pod负载均衡的问题

使用

1
vim deploy.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
apiVersion: apps/v1
kind: Deployment
metadata:
name: hostnames
spec:
selector:
matchLabels:
app: hostnames
replicas: 3
template:
metadata:
labels:
app: hostnames
spec:
containers:
- name: hostnames
image: mirrorgooglecontainers/serve_hostname
ports:
- containerPort: 9376
protocol: TCP
1
2
3
kubectl apply -f deploy.yml

kubectl get pods
1
2
3
4
NAME                         READY   STATUS    RESTARTS   AGE
hostnames-69cd56f6d5-cgmmk 1/1 Running 0 18m
hostnames-69cd56f6d5-nnjqp 1/1 Running 0 18m
hostnames-69cd56f6d5-vcp4s 1/1 Running 0 18m
1
vim service-v1.yml
1
2
3
4
5
6
7
8
9
10
11
12
apiVersion: v1
kind: Service
metadata:
name: hostnames
spec:
selector:
app: hostnames
ports:
- name: default
protocol: TCP
port: 80
targetPort: 9376
1
2
3
kubectl apply -f service-v1.yml

kubectl get svc hostnames
1
2
NAME        TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
hostnames ClusterIP 10.109.68.71 <none> 80/TCP 118s

Service是通过selector来找到相应标签的Pod 解决了IP依赖的问题

特性

  • 上述ClusterIP类型的Service只能在集群内部访问
1
2
curl 10.109.68.71:80
# curl: (7) Failed to connect to 10.109.68.71 port 80: Connection timed out
  • 想要在集群外部访问的一个方式是NodePort 既使用节点上的某个特定端口
1
vim service-v2.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: v1
kind: Service
metadata:
name: hostnames
spec:
type: NodePort
selector:
app: hostnames
ports:
- name: default
protocol: TCP
port: 80
targetPort: 9376
1
2
3
kubectl apply -f service-v2.yml

kubectl get svc hostnames
1
2
NAME        TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
hostnames NodePort 10.109.68.71 <none> 80:32284/TCP 3m2s
1
2
3
4
5
6
7
8
curl 172.10.66.201:32284
# hostnames-69cd56f6d5-vcp4s

curl 172.10.66.201:32714
# hostnames-69cd56f6d5-cgmmk

curl 172.10.66.201:32714
# hostnames-69cd56f6d5-nnjqp

Service同时解决了Pod水平扩展后的负载均衡问题