按照下面的文档完成 service 实验

https://www.cnblogs.com/backups/p/k8s_1.html#service

Service 的作用:

提供服务的自动发现和负载均衡
因为 Pod 随时会被销毁和重新创建、并且每个 Pod 会通过调度器将其部署到不同的 N 个 Node 节点,这样会导致 Pod ip 地址会发生变化。所以需要通过 Service 去发现 Pod 并获取其 IP 地址。

Service 的类型:

  • ClusterIP:默认类型,自动分配一个仅Cluster内部可以访问的虚拟IP
  • NodePort:在ClusterIP基础上为Service在每台机器上绑定一个端口,外部可以通过NodeIP:NodePort来访问该服务
  • LoadBalancer:在NodePort的基础上,借助cloud provider创建一个外部负载均衡器,并将请求转发到NodeIP:NodePort
  • ExternalName:把集群外的服务引入到集群内部,在集群内部直接使用

Service 实践

编写 service yaml 文件

service cat k8s_svc.yml
apiVersion: v1
kind: Service           # 简称svc
metadata:
  name: myweb
spec:
  type: NodePort        # 端口映射类型,默认ClusterIP类型
  #clusterIP:10.254.1.1
  ports:
    - port: 80          # clusterIP port
      nodePort: 30000   # node port 默认30000-32767
      targetPort: 80    # pod port
  selector:             # 选择器。当有多个Pod的时候,需要使用选择器选择为那些Pod做负载均衡。和RC一样,使用标签选择器。
    app: myweb

创建 service

service kubectl create -f k8s_svc.yml
service/myweb created

查看创建的 service 的状态

service kubectl get svc myweb
NAME    TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
myweb   NodePort   10.107.181.57   <none>        80:30000/TCP   3m3s

查看创建的 service 的详细信息

service kubectl describe svc myweb
Name:                     myweb
Namespace:                default
Labels:                   <none>
Annotations:              <none>
Selector:                 app=myweb
Type:                     NodePort
IP:                       10.107.181.57
Port:                     <unset>  80/TCP
TargetPort:               80/TCP
NodePort:                 <unset>  30000/TCP
Endpoints:                <none>
Session Affinity:         None
External Traffic Policy:  Cluster

k8s 在创建 service 的同时,还会自动创建跟 service 同名的 endpoints

➜ kubectl get endpoints nginx-deployment -o yaml
apiVersion: v1
kind: Endpoints
metadata:
  annotations:
    endpoints.kubernetes.io/last-change-trigger-time: "2021-02-25T10:00:08Z"
  creationTimestamp: "2021-02-25T10:00:08Z"
  labels:
    app: nginx
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
      ...
      ...
      ...

升级

kubectl rolling-update nginx -f k8s_rc2.yaml --update-period=5s

回滚

kubectl rolling-update nginx2 -f k8s_rc.yaml --update-period=1s
Logo

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

更多推荐