3. 服务发现

3.1 设置Pod的hostname与subdomain

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 编写Yaml文件
apiVersion: v1
kind: Service
metadata:
name: default-subdomain
spec:
selector:
app: nginx
clusterIP: None
ports:
- name: nginx
port: 80
targetPort: 80
---
apiVersion: v1
kind: Pod
metadata:
name: nginx-hostname
labels:
app: nginx
spec:
hostname: nginx-1
subdomain: default-subdomain
containers:
- image: nginx
name: nginx
imagePullPolicy: IfNotPresent

解析Service Name

1
2
3
4
5
# 创建busybox应用
kubectl run busybox --image=busybox:1.28 --image-pull-policy=IfNotPresent --command sleep 36000

# 执行解析操作
kubectl exec -it busybox -- nslookup default-subdomain

查看node的角色

1
kubectl get nodes

3.2 HostAliases

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 编写Yaml文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: deployment-nginx
spec:
replicas: 4
selector:
matchLabels:
app: pod-nginx
template:
metadata:
labels:
app: pod-nginx
spec:
hostAliases:
- ip: "127.0.0.1"
hostnames:
- "foo.local"
- "bar.local"
- ip: "10.1.2.3"
hostnames:
- "foo.remote"
- "bar.remote"
containers:
- name: nginx
image: nginx:1.7.6
ports:
- containerPort: 80

3.3 Pod的DNS设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 编写Yaml文件
apiVersion: v1
kind: Pod
metadata:
namespace: default
name: dns-example
spec:
containers:
- name: test
image: nginx
dnsPolicy: "None"
dnsConfig:
nameservers:
- 1.2.3.4
searches:
- ns1.svc.cluster-domain.example
- my.dns.search.suffix
options:
- name: ndots
value: "2"
- name: edns0

# 在容器test的/etc/resolv.conf文件中获取以下内容
nameserver 1.2.3.4
search ns1.svc.cluster-domain.example my.dns.search.suffix
options ndots:2 edns0