Service概述

Service在Kubernetes中提供了一种抽象的方式来公开应用程序的网络访问,并提供了负载均衡和服务发现等功能,使得应用程序在集群内外都能够可靠地进行访问。

每个Service都会自动关联一个对应的Endpoint。当创建一个Service时,Kubernetes会根据Service的选择器(selector)来找到匹配的Pod,并将这些Pod的IP地址和端口信息作为Endpoint的一部分。当Service接收到来自外部或内部的请求时,它会将请求转发到与之关联的Endpoint。Endpoint中包含了后端Pod的IP地址和端口信息,Service会根据负载均衡算法将请求转发到一个或多个后端Pod上。并且Service会自动关联到防火墙规则, 将pod的地址和端口保存在防火墙规则内

以上内容由gtp生成

举个例子,以前我访问pod资源要一个一个访问,现在我把一堆具有相同特征(如标签)的pod绑定一个service,然后在service内侧与pod端口绑定,service外侧映射一个端口到宿主机,service还能改dns改防火墙规则。这样直接访问宿主机的端口就能访问到一组pod的特定端口。跟nginx做反向代理负载均衡差不多

#查看帮助
kubectl explain Service
apiVersion   <string>
kind <string>
metadata     <Object>
spec <Object>
status       <Object>

kubectl explain Service.spec
allocateLoadBalancerNodePorts  <boolean>#是否是默认映射端口nodeports
#如果是,则会默认分配到30000-32767随机一个
clusterIP    <string>   #service的虚拟ip地址
externalIPs  <[]string> #公开到集群外的ip
externalName <string> #指定外部dns名称
externalTrafficPolicy <string> #定义外部流量策略,可选cluster或local
healthCheckNodePort  <integer> #用于健康检查的端口
sessionAffinity <string>  #会话策略,可选ClientIP或者None
type <string>  #类型,有四种,ExternalName, ClusterIP, NodePort, LoadBalancer
ports        <[]Object>

kubectl explain service.spec.ports
name <string>
nodePort     <integer> #对外映射的端口
port <integer> -required- #service的端口
protocol     <string> #可选SCTP、TCP、UDP

#在node上下载旧版本的nginx
ctr images pull docker.io/library/nginx:1.21
#创建被管理的pod的yaml文件
#
mkdir service
cd service
cat > pod.yaml << EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pods
spec:
  replicas: 2
  selector:
    matchLabels:
      nginx: "1.21"
  template:
    metadata:
      labels:
        nginx: "1.21"
    spec:
      containers:
        - name: test1
          image: docker.io/library/nginx:1.21
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 80
          startupProbe:
            periodSeconds: 5
            initialDelaySeconds: 20
            timeoutSeconds: 5
            httpGet:
              scheme: HTTP
              port: 80
              path: /
          livenessProbe:
            periodSeconds: 5
            initialDelaySeconds: 20
            timeoutSeconds: 5
            httpGet:
              scheme: HTTP
              port: 80
              path: /
          readinessProbe:
            periodSeconds: 5
            initialDelaySeconds: 20
            timeoutSeconds: 5
            httpGet:
              scheme: HTTP
              port: 80
              path: /        
EOF
kubectl apply -f pod.yaml
#成功运行,就不去用curl验证了
kubectl get pods -w
NAME                   READY   STATUS    RESTARTS   AGE
pods-8599b54cf-6tzrx   0/1     Running   0          12s
pods-8599b54cf-vhxd8   0/1     Running   0          12s
pods-8599b54cf-6tzrx   0/1     Running   0          25s
pods-8599b54cf-vhxd8   0/1     Running   0          25s
pods-8599b54cf-6tzrx   1/1     Running   0          25s
pods-8599b54cf-vhxd8   1/1     Running   0          25s

ClusterIP模式

### ClusterIP模式仅允许集群内部访问
#创建servicea-clusterip.yaml
cat > service-clusterip.yaml << EOF
apiVersion: v1
kind: Service
metadata:
  name: service
spec:
  type: ClusterIP
  ports:
   - port: 80 #service内侧端口
     protocol: TCP
     targetPort: 80 #对应的pod的端口
  selector:    #筛选器,匹配标签nginx="1.21"的pod
     nginx: "1.21"
EOF
kubectl apply -f service.yaml
kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP   12d
service      ClusterIP   10.107.178.176   <none>        80/TCP    31s
#查看Endpoint列表
#只有完成就绪探测的pod才会被service接管,才会被加入endpoint列表中。未完成启动探测的pod也不会
kubectl describe service service | grep Endpoint
Endpoints:         10.10.179.1:80,10.10.234.86:80
kubectl get ep service #也可以
NAME      ENDPOINTS                        AGE
service   10.10.179.1:80,10.10.234.86:80   2m54s
#测试
curl 10.10.179.1:80
#service自动生成域名,仅在pod内可以进行访问
service.default.svc.cluster.local:80
#进入pod
kubectl exec pods-8599b54cf-6tzrx -it -- /bin/sh
curl service.default.svc.cluster.local:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="<http://nginx.org/>">nginx.org</a>.<br/>
Commercial support is available at
<a href="<http://nginx.com/>">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
#清理
kubectl delete -f service-clusterip.yaml

nodeport模式

#nodeport允许将ServiceIp映射到宿主机外部
#创建service-nodeport.yaml
cat > service-nodeport.yaml << EOF
apiVersion: v1
kind: Service
metadata:
  name: service
spec:
  type: NodePort
  ports:
   - port: 80
     protocol: TCP
     targetPort: 80  #对应的pod的端口
     nodePort: 30080 #映射到物理机的端口,如果不写,会随机分配到30000-32767之间的一个
  selector:          #筛选器,匹配标签nginx="1.21"的pod
     nginx: "1.21"
EOF
kubectl apply -f service-nodeport.yaml
kubectl get svc
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP        12d
service      NodePort    10.108.9.134   <none>        80:30080/TCP   11s
#通过宿主机直接请求如图
ipvsadm -Ln | grep 30080 -A 2
TCP  172.17.0.1:30080 rr
  -> 10.10.179.1:80               Masq    1      0          0
  -> 10.10.234.86:80              Masq    1      0          0
--
TCP  192.168.8.160:30080 rr
  -> 10.10.179.1:80               Masq    1      0          1
  -> 10.10.234.86:80              Masq    1      0          0
--
TCP  192.168.122.1:30080 rr
  -> 10.10.179.1:80               Masq    1      0          0
  -> 10.10.234.86:80              Masq    1      0          0
--
TCP  10.10.189.192:30080 rr
  -> 10.10.179.1:80               Masq    1      0          0
  -> 10.10.234.86:80              Masq    1      0          0
kubectl delete -f service-nodeport.yaml

ExternalName模式

充当一个别名,将服务映射到集群外部的一个外部域名。当使用该服务时,Kubernetes会将服务的DNS解析为ExternalName指定的外部域名,从而实现对外部服务的访问。这种模式适用于需要将服务与集群外部的现有服务进行关联的场景。

#用以跨namespace调用资源
#创建一个新的ns
kubectl create ns server
#创建server中的yaml文件
cat > pod-in-server.yaml << EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pods
  namespace: server
spec:
  replicas: 2
  selector:
    matchLabels:
      nginx: "1.21"
  template:
    metadata:
      labels:
        nginx: "1.21"
    spec:
      containers:
        - name: test1
          image: docker.io/library/nginx:1.21
          imagePullPolicy: IfNotPresent
EOF
kubectl apply -f pod-in-server.yaml
#创建pod in server中的service四层代理
cat > service-in-server.yaml << EOF
apiVersion: v1
kind: Service
metadata:
  name: service-in-server
  namespace: server
spec:
  selector:
     nginx: "1.21"
  ports:
   - name: http
     protocol: TCP
     port: 80
     targetPort: 80
EOF
kubectl apply -f service-in-server.yaml
#创建default中的service,设置为externalname
cat > service-externalname.yaml << EOF
apiVersion: v1
kind: Service
metadata:
  name: service
spec:
  type: ExternalName
  externalName: service-in-server.server.svc.cluster.local #设置要关联的service的域名
  ports:
   - port: 80
  selector: 
     nginx: "1.21"
EOF
kubectl apply -f service-externalname.yaml
kubectl get pods -n server
NAME                    READY   STATUS    RESTARTS   AGE
pods-8649769f54-fs72b   1/1     Running   0          22s
#进入默认的ns的pod中,通过域名访问server的ns中的pod资源
kubectl exec pods-8599b54cf-6tzrx -it -- /bin/sh
curl service-in-server.server.svc.cluster.local
#可以访问到
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="<http://nginx.org/>">nginx.org</a>.<br/>
Commercial support is available at
<a href="<http://nginx.com/>">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

#清理
kubectl delete -f service-externalname.yaml
kubectl delete -f service-in-server.yaml
kubectl delete -f pod-in-server.yaml

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐