设置PodName到环境变量实验

实验的目标是将Pod的名称放在环境变量POD_NAME中,这样就可以在代码中、数据卷挂载时使用该环境变量。

第一个Deployment:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment1
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.7.9
          ports:
            - containerPort: 80

第二个Deployment:

 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

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment2
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.7.9
          ports:
            - containerPort: 80
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.name

分别查看两个Pod的POD_NAME环境变量:

1
2
3
4
5
6
7

# 无输出
kubectl exec -it nginx-deployment1-5d59d67564-w22m7 -- bash -c 'echo $POD_NAME'

# 输出:nginx-deployment2-77996f47cb-hpmd2
kubectl exec nginx-deployment2-77996f47cb-hpmd2 -- bash -c 'echo $POD_NAME'

使用kubectl exec pod_name -- bash -c 'echo $POD_NAME'时需要注意,必须使用单引号,我目前还不知道为什么。

参考资料

  1. kubernetes之如何在POD外执行复杂shell命令