k8s跨namespace访问服务

情况:v2 namespace需要访问default namespace的rabbitmq服务

解决办法:在v2 namespace里面创建service,不指定selector, 采用type=ExternalName的方式,externalName定义成为指向namespace=default中的rabbitmq-service

# vi rabbitmq.yaml 
apiVersion: v1
kind: Service
metadata:
 name: rabbitmq
 namespace: v2
spec:
 ports:
 - port: 5672
   name: amqp
 sessionAffinity: None
 type: ExternalName
 externalName: rabbitmq.default.svc.cluster.local

[root@bdy-master1]# kubectl create -f rabbitmq.yaml

[root@bdy-master1]# kubectl get service -A |grep rabbit

default rabbitmq ClusterIP None <none> 5672/TCP 108d

default rabbitmq-service NodePort 10.254.252.174 <none> 15672:32001/TCP,5672:32002/TCP 115d

v2 rabbitmq ExternalName <none> rabbitmq.default.svc.cluster.local 5672/TCP 25h

测试是否可以跨namespace访问

[root@bdy-master1 rabbitmq-service]# kubectl exec -it -n v2 api-57596df5b8-sx2hc sh

/var/www/html # nslookup rabbitmq

nslookup: can't resolve '(null)': Name does not resolve

Name: rabbitmq

Address 1: 172.30.28.24 172-30-28-24.rabbitmq.default.svc.cluster.local

Address 2: 172.30.3.4 rabbitmq-1.rabbitmq.default.svc.cluster.local

Address 3: 172.30.43.8 172-30-43-8.rabbitmq.default.svc.cluster.local

Address 4: 172.30.43.2 rabbitmq-2.rabbitmq.default.svc.cluster.local

Address 5: 172.30.3.30 172-30-3-30.rabbitmq.default.svc.cluster.local

Address 6: 172.30.28.2 rabbitmq-0.rabbitmq.default.svc.cluster.local

/var/www/html # ping rabbitmq

PING rabbitmq (172.30.43.2): 56 data bytes

64 bytes from 172.30.43.2: seq=0 ttl=62 time=0.720 ms

64 bytes from 172.30.43.2: seq=1 ttl=62 time=0.650 ms

^C

--- rabbitmq ping statistics ---

2 packets transmitted, 2 packets received, 0% packet loss

round-trip min/avg/max = 0.650/0.685/0.720 ms

/var/www/html # nc -n -v rabbitmq 5672

rabbitmq (172.30.43.2:5672) open

^[[A^Cpunt!

 

上一篇:K8S-Serivce的原理和实践


下一篇:安卓svc命令使用总结