Kubernetes中的服務是一個抽象,它定義了一組邏輯Pod和一個訪問它們的策略。服務容許從屬Pod之間的鬆散耦合。與全部Kubernetes對象同樣,使用YAML (首選)或JSON 定義服務。服務所針對的Pod集合一般由LabelSelector肯定。node
儘管每一個Pod都具備惟一的IP地址,但若是沒有服務,這些IP不會在羣集外部公開。服務容許您的應用程序接收流量。經過type
在ServiceSpec中指定a ,能夠以不一樣方式公開服務:bash
<NodeIP>:<NodePort>
。ClusterIP的超集。externalName
經過返回帶有名稱的CNAME記錄,使用任意名稱(在規範中指定)公開服務。沒有代理使用。此類型須要v1.7或更高版本kube-dns
。
[root@master ~]# kubectl get deployments NAME READY UP-TO-DATE AVAILABLE AGE kubernetes-bootcamp 1/1 1 1 4h12m
[root@master ~]# kubectl expose deployment/kubernetes-bootcamp --type="NodePort" --port 8080 service/kubernetes-bootcamp exposed
[root@master ~]# kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 2d12h kubernetes-bootcamp NodePort 10.98.200.115 <none> 8080:31238/TCP 16s
查看詳細信息app
[root@master ~]# kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 2d13h kubernetes-bootcamp NodePort 10.98.200.115 <none> 8080:31238/TCP 12m [root@master ~]# kubectl describe service/kubernetes-bootcamp Name: kubernetes-bootcamp Namespace: default Labels: run=kubernetes-bootcamp Annotations: <none> Selector: run=kubernetes-bootcamp Type: NodePort IP: 10.98.200.115 Port: <unset> 8080/TCP TargetPort: 8080/TCP NodePort: <unset> 31238/TCP Endpoints: 10.244.0.15:8080 Session Affinity: None External Traffic Policy: Cluster Events: <none>
[root@master ~]# export NODE_PORT=$(kubectl get services/kubernetes-bootcamp -o go-template='{{(index .spec.ports 0).nodePort}}') [root@master ~]# echo NODE_PORT=$NODE_PORT NODE_PORT=31238
[root@master ~]# curl http://192.168.0.10:31238 Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-7f56b875dc-6zbjt | v=1
[root@master ~]# export POD_NAME=$(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}')
[root@master ~]# echo Name of the Pod: $POD_NAME Name of the Pod: kubernetes-bootcamp-7f56b875dc-6zbjt
[root@master ~]# kubectl label pod $POD_NAME app=v1 pod/kubernetes-bootcamp-7f56b875dc-6zbjt labeled
[root@master ~]# kubectl get pods NAME READY STATUS RESTARTS AGE kubernetes-bootcamp-7f56b875dc-6zbjt 1/1 Running 0 4h52m
[root@master ~]# kubectl describe pods Name: kubernetes-bootcamp-7f56b875dc-6zbjt Namespace: default Priority: 0 PriorityClassName: <none> Node: master/192.168.0.10 Start Time: Fri, 25 Jan 2019 09:55:50 +0800 Labels: app=v1
[root@master ~]# kubectl get pods -l app=v1 NAME READY STATUS RESTARTS AGE kubernetes-bootcamp-7f56b875dc-6zbjt 1/1 Running 0 4h55m
kubectl delete service -l run=kubernetes-bootcamp