天天看點

K8s之Servicet學習筆記

## service

--pod-network-cidr=10.244.0.0/16 (pod網段)

--service-cidr=10.96.0.0/12 (service網段)

```

[root@master maintest]# cat pod.yaml

apiVersion: apps/v1

kind: Deployment

metadata:

 name: my-nginx

spec:

 selector:

   matchLabels:

     run: my-nginx

 replicas: 2

 template:

   metadata:

     labels:

       run: my-nginx

   spec:

     containers:

     - name: my-nginx

       image: nginx

       ports:

       - containerPort: 80

service 預設type類型為ClusterIP

[root@master maintest]# cat service.yaml

apiVersion: v1

kind: Service

 labels:

   run: my-nginx

 ports:

 - port: 80

   protocol: TCP

service 代理到對應的後端pod

### 映射到主控端端口

**.service.spec.type**

 **NodePort**

 type: NodePort

[root@master maintest]# kubectl get svc -o wide

NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE   SELECTOR

kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        69d   <none>

my-nginx     NodePort    10.106.132.151   <none>        80:30994/TCP   21h   run=my-nginx

**通路node節點的ip:30994---->service ip:80---->pod ip:80**

### 建立沒有selector的service

[root@master maintest]# cat noselector.yaml

 name: my-service

   targetPort: 3306

endpoint.yaml

[root@master maintest]# cat endpoint.yaml

kind: Endpoints

subsets:

- addresses:

 - ip: 1.2.3.4

 - port: 3306

[root@master maintest]# kubectl describe svc my-service

Name:              my-service

Namespace:         default

Labels:            <none>

Annotations:       <none>

Selector:          <none>

Type:              ClusterIP

IP Families:       <none>

IP:                10.104.205.156

IPs:               <none>

Port:              <unset>  80/TCP

TargetPort:        3306/TCP

Endpoints:         1.2.3.4:3306

Session Affinity:  None

Events:            <none>

### 建立type是ExternalName的service

[root@master maintest]# cat external.yaml

 namespace: prod

 type: ExternalName

 externalName: my.database.example.com

繼續閱讀