service
测试用例
kubectl create deploy test-web --image=python -- python -m http.server
depoy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: test-web
name: test-web
spec:
replicas: 1
selector:
matchLabels:
app: test-web
template:
metadata:
labels:
app: test-web
spec:
containers:
- command:
- python
- -m
- http.server
image: python
name: python
ClusterIP
只能在集群内部访问服务
类型一:默认类型
kubectl expose deploy test-web --port=80 --protocol=TCP --target-port=8000 --type=ClusterIP
svc.yaml
apiVersion: v1
kind: Service
metadata:
labels:
app: test-web
name: test-web
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8000
selector:
app: test-web
type: ClusterIP
类型二:cluserIP=None这种类型常用于statefulset中。当访问此类应用时,svc不做负载均衡而是将域名直接解析为后端的pod
svc.yaml
apiVersion: v1
kind: Service
metadata:
labels:
app: test-web
name: test-web
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8000
selector:
app: test-web
clusterIP: None
type: ClusterIP
类型三: 不带selector指令,常用于访问集群外的服务
svc.yaml
apiVersion: v1
kind: Service
metadata:
name: test-web-noselector
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8000
type: ClusterIP
---
apiVersion: v1
kind: Endpoints
metadata:
name: ep-01
subsets:
- addresses:
- ip: 10.4.7.1
ports:
- port: 8000
NodePort
在ClusterIP的基础上增加了对外访问的端口。既可以在集群内访问又可以在集群外通过nodePort 访问
kubectl expose deploy test-web --port=80 --protocol=TCP --target-port=8000 --type=NodePort
svc.yaml
apiVersion: v1
kind: Service
metadata:
labels:
app: test-web
name: test-web
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8000
selector:
app: test-web
type: NodePort
LoadBalancer
ExternalName
session 亲和性
如果要确保每次都将来自特定客户端的连接传递到同一 Pod, 则可以通过将 service.spec.sessionAffinity 设置为 "ClientIP" (默认值是 "None"),来基于客户端的 IP 地址选择会话关联。
你还可以通过适当设置 service.spec.sessionAffinityConfig.clientIP.timeoutSeconds 来设置最大会话停留时间。 (默认值为 10800 秒,即 3 小时)
apiVersion: v1
kind: Service
metadata:
name: nodeport-type
spec:
type: ClusterIP
sessionAffinity: ClientIP
sessionAffinityConfig:
clientIP: 10800
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80