Kubernetes

K8S Service

本文主要是介绍K8S Service,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1 Service的作用

  1. 服务发现,防止Pod失联
  2. 定义Pod的访问策略,负载均衡

本质是创建Servicer后Kube-proxy生成一套访问规则存储到ETCD,本质生效的是这套访问规则,Service只是表象!

2 Pod与Service关联

Service与Pod,就像Deployment与Pod的关联一样,都是通过labels进行关联。

image-20210630221827033

3 常用Service类型

kubectl expose --help

image-20210630222217496

image-20210630235031064

ClusterIP:集群的内部使用

NodePort:用于对外暴露端口进行访问

LoadBalancer:对外访问应用使用,公有云

3.1 创建ClusterIP的Service实例

先创建Controller控制的Pod

vim web-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: web
  name: web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: web
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}
kubectl apply -f web-deployment.yaml

创建

vim web-service.yaml
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: web
  name: web-service
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: web
status:
  loadBalancer: {}

Service默认即是ClusterIP

kubectl apply -f web-service.yaml
kubectl get svc
NAME          TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
kubernetes    ClusterIP   10.96.0.1      <none>        443/TCP   5d22h
web-service   ClusterIP   10.98.145.89   <none>        80/TCP    5s

到任意节点访问

curl 10.98.145.89

image-20210630225257875

3.2 创建NodePort的Service

vim web1-service.yaml
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: web
  name: web1-service
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: web
  type: NodePort
status:
  loadBalancer: {}
kubectl apply -f web1-service.yaml
kubectl get svc

image-20210630231519820

这篇关于K8S Service的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!