0%

k8s_Service

Service

Services Types

  • NodePort
  • ClusterIP: the service create a virtual IP inside the cluster enable communication between different services such as a set of frontend services and a set of backend services.
  • LoadBalancer

NodePort

A service can help us by mapping a port on the node to a port on the pod.

port的类型

  • tatgetPort:在pod上的web server运行在80端口(pod的port)
  • port:service自身的port (service有自己的ip地址,也称做clusterIP of the service)
  • NodePort:在node上的port,用户实际连接的port(有效范围:30000-32767)

模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
type: NodePort
ports:
- targetPort: 80
port: 80
nodePort: 30008
selector:
labels:
app: myapp
type: front-end

selector:目的是把service和特定的pod联系到一起。(由于targetPort相同的pod也许会很多,因此使用pod的labels进行选择)

Example

  • 首先创建deployment.yaml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: myapp-deployment
    labels:
    tier: frontend
    app: nginx
    spec:
    selector:
    matchLabels:
    app: myapp
    replicas: 3
    template:
    metadata: nginx-2
    labels:
    app: myapp
    spec:
    containers:
    - name: nginx
    image: nignx

    kubectl create -f deployment.yaml

  • 创建service

    service-definition.yaml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    apiVersion: v1
    kind: Service
    metadata:
    name: myapp-service
    spec:
    type: NodePort
    ports:
    - targetPort: 80
    port: 80
    nodePort: 30004
    selector: #关键:靠selector来把service和特定pod关联起来
    app: myapp #要关联的pod的metadata.labels的内容

    selector作用: link the Service to the PODs created by the deployment.

  • 创建service

    kubectl create -f service-definition.yaml

  • 查看当前service

    kubectl get svc

  • 使用minikube的情况下,查看 nodeIP:port 的值 能访问到当前的pod中的服务

    minikube service myapp-service --url

ClusterIP

  • service的默认选项
  • 为node中运行的一组相同的pod提供统一的interface和ip地址

frontend server 前端需要和后端通信

backend server 后端需要和redis通信

redis(k-v store)

由于一组相同pod(比如前端),它们的ip address是动态的(pod会挂,会重建),kubernetes service 为这一组pod提供了一个单独的interface去让其他pod能连接这个组里面的pod。

比如,为backend的pods创建一个service,这个serivce会把所有的bakend pods 组成一组并为其他的pod(front end)提供一个单独的interface去连接该backend的service。

Example

service-definition.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: v1
kind: Service
metadata:
name: back-end
spec:
type: ClusterIP
ports:
- targetPort: 80
port: 80

selector: #通过selector来找到要为哪些pod去创建clusterIP
app: myapp #这里同样是pod的labels的内容
type: back-end

pod-definition.yaml

1
2
3
4
5
6
7
8
9
10
11
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
type: back-end
spec:
containers:
- name: nginx-container
image: nginx