Kubernetes-Service
Service
一种访问Pod的策略,其他的Pod可以通过这个Service访问到这个Service代理的Pod。
apiVersion: v1
kind: Service
metadata:
labels:
app: nginx
name: nginx
namespace: default
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: nginx
sessionAffinity: None
type: ClusterIP
Service类型:
- ClusterIP:集群内部使用,默认使用
- NodePort:在所有安装了kube-proxy的节点上打开一个端口,此端口可以代理至后端Pod,然后集群外部可以使用节点的IP地址和NodePort的端口号访问到集群Pod的服务。NodePort默认端口访问:30000-32767
- LoadBalance:会用云提供商的负载均衡器公开服务。
- ExternalName: 通过返回定义的CNAME别名
代理k8s外部服务
apiVersion: v1
kind: Service
metadata:
labels:
app: nginx-svc-external
name: nginx-svc-external
spec:
ports:
- name: http
port: 80
protocol: TCP
targetPort: 80
sessionAffinity: None
type: ClusterIP
---
apiVersion: v1
kind: Endpoints
metadata:
labels:
app: nginx-svc-external
name: nginx-svc-external
namespace: default
subsets:
- addresses:
- ip: 220.181.38.251
ports:
- name: http
port: 80
protocol: TCP
要确保Endpoints和Service的name和labels名字相同,还有port的名字、端口、协议相同才能匹配
$ kubectl get ep
NAME ENDPOINTS AGE
nginx 172.16.107.204:80,172.16.169.139:80 4h22m
nginx-svc-external 220.181.38.251:80 8m20s
$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
nginx ClusterIP 10.0.0.252 <none> 80/TCP 4h22m
nginx-svc-external ClusterIP 10.0.0.105 <none> 80/TCP 8m29s
Pod访问service名称或者ClusterIP,测试service能否正常代理外部的百度地址
$ curl baidu.com -I
HTTP/1.1 200 OK
Date: Wed, 12 Jan 2022 05:49:19 GMT
Server: Apache
Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
ETag: "51-47cf7e6ee8400"
Accept-Ranges: bytes
Content-Length: 81
Cache-Control: max-age=86400
Expires: Thu, 13 Jan 2022 05:49:19 GMT
Connection: Keep-Alive
Content-Type: text/html
$ curl 10.0.0.105 -I
HTTP/1.1 200 OK
Date: Wed, 12 Jan 2022 05:49:07 GMT
Server: Apache
Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
ETag: "51-47cf7e6ee8400"
Accept-Ranges: bytes
Content-Length: 81
Cache-Control: max-age=86400
Expires: Thu, 13 Jan 2022 05:49:07 GMT
Connection: Keep-Alive
Content-Type: text/html