上一章我们分享了k8s的网络代理模式,今天我们来分享一下k8s中的服务发现。
1.环境变量模式的服务发现
k8s默认为我们提供了通过环境变量来实现服务发现的功能,前提是
1.需要service在pod之前创建
2.适用于同一命名空间
1.1创建service
[root@localhost ~]# cat netcore-service.yaml apiVersion: v1 kind: Service metadata: name: netcore-service labels: app: netcore spec: ports: - name: http protocol: TCP port: 1001 targetPort: 1000 nodePort: 31111 selector: app: cys-netcore type: NodePort
kubectl create -f netcore-service.yaml
1.2创建pod
[root@localhost ~]# cat netcore.yaml apiVersion: apps/v1beta2 kind: Deployment metadata: name: cys-netcore spec: replicas: 1 selector: matchLabels: app: cys-netcore template: metadata: labels: app: cys-netcore spec: containers: - name: cys-netcore image: chenyishi/webdocker_s_provider ports: - containerPort: 1000 env: - name: serverpo
kubectl create -f netcore.yaml
1.3验证
查看环境变量
我们再以相同的方式再创建一组pod+service
[root@localhost ~]# cat netcore2.yaml apiVersion: apps/v1beta2 kind: Deployment metadata: name: cys-netcore2 spec: replicas: 1 selector: matchLabels: app: cys-netcore2 template: metadata: labels: app: cys-netcore2 spec: containers: - name: cys-netcore2 image: chenyishi/webdocker_s_provider ports: - containerPort: 1000 env: - name: serverport value: "1000"
[root@localhost ~]# cat netcore-service2.yaml apiVersion: v1 kind: Service metadata: name: netcore-service2 labels: app: netcore2 spec: ports: - name: http protocol: TCP port: 1002 targetPort: 1000 nodePort: 31112 selector: app: cys-netcore2 type: NodePort
kubectl create -f netcore-service2.yaml
kubectl create -f netcore2.yaml
查看env
我们进入容器,调用一下第一个service
至此,我们证明了可以通过env使service互通