kubernetes 服务发现机制:环境变量和DNS
1. 环境变量
创建pod资源时,kubectl会将其所属名称空间内的每个活动的service对象以一系列环境变量的形式注入其中。
但是也仅仅只是注入创建时候的资源,后面的变化它时不感知的。
我有个game服务:
qiteck@server:~$ sudo kubectl get service | grep game
game NodePort 10.96.122.100 <none> 9300:9300/TCP 45h
进入另外一个k8s网络内的pod:
export | grep GAME
qiteck@server:~$ sudo kubectl exec -it gateway-8df8488d5-tgdq6 -- /bin/bash
root@gateway-8df8488d5-tgdq6:/usr/local/openresty# export | grep GAME
declare -x GAME_PORT="tcp://10.96.122.100:9300"
declare -x GAME_PORT_9300_TCP="tcp://10.96.122.100:9300"
declare -x GAME_PORT_9300_TCP_ADDR="10.96.122.100"
declare -x GAME_PORT_9300_TCP_PORT="9300"
declare -x GAME_PORT_9300_TCP_PROTO="tcp"
declare -x GAME_SERVICE_HOST="10.96.122.100"
declare -x GAME_SERVICE_PORT="9300"
declare -x GAME_SERVICE_PORT_PORT="9300"
kubernets为每个service资源生成包括以下形式的环境变量在哪的一系列环境变量,在同一名称空间内创建的pod对象都会自动拥有这些变量: {SERVICE_NAME}_SERVICE_HOST, {SERVICE_NAME}_SERVICE_PORT
2. coredns
该主键详情见之前文章 <<kubernetes CoreDNS服务发现组件研究>>
dig srv game.default.svc.cluster.local
root@advertise-56d599d999-c7td4:/var/app/mage-advertise# dig srv game.default.svc.cluster.local
; <<>> DiG 9.16.37-Debian <<>> srv game.default.svc.cluster.local
;; global options: +cmd
;; Got answer:
;; WARNING: .local is reserved for Multicast DNS
;; You are currently testing what happens when an mDNS query is leaked to DNS
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 62959
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 2
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: 996ee0ab446f6520 (echoed)
;; QUESTION SECTION:
;game.default.svc.cluster.local. IN SRV
;; ANSWER SECTION:
game.default.svc.cluster.local. 30 IN SRV 0 100 9300 game.default.svc.cluster.local.
;; ADDITIONAL SECTION:
game.default.svc.cluster.local. 30 IN A 10.96.122.100
;; Query time: 0 msec
;; SERVER: 10.96.0.10#53(10.96.0.10)
;; WHEN: Wed Apr 26 15:02:50 CST 2023
;; MSG SIZE rcvd: 197
可以看到:9300 game.default.svc.cluster.local, 服务和端口都能找到
dig无法使用dns配置/etc/resolv.conf
more /etc/resolv.conf
root@advertise-56d599d999-c7td4:/var/app/mage-advertise# more /etc/resolv.conf
search default.svc.cluster.local svc.cluster.local cluster.local qiteck.net localdomain
nameserver 10.96.0.10
options ndots:5
ping和telnet可以用上/etc/resolv.conf的search域名:
telnet game 9300
root@advertise-56d599d999-c7td4:/var/app/mage-advertise# telnet game 9300
Trying 10.96.122.100...
Connected to game.default.svc.cluster.local.
Escape character is '^]'.
^C^Z^C
Connection closed by foreign host.
ping game
root@advertise-56d599d999-c7td4:/var/app/mage-advertise# ping game
PING game.default.svc.cluster.local (10.96.122.100) 56(84) bytes of data.
^C
--- game.default.svc.cluster.local ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms
ping/telnet会根据/etc/resolv.conf的search补齐搜索的域名