Kubernetes部署中如何正确引用容器字段作为环境变量?
Hey there! Let's sort out why your environment variable isn't working as expected. The core issue here is that you're using a field path pointing to the Deployment's spec template instead of the Pod's own spec when leveraging fieldRef.
When you use valueFrom.fieldRef in a container's environment variables, the fieldPath always references fields from the Pod object that gets created from your Deployment template—not the Deployment resource itself. Your original path spec.template.spec.containers[0].name targets the Deployment's structure, which doesn't exist in the context of the running Pod.
The Correct Field Path
To reference the name of the first container in the Pod (which matches the container you're defining this env var in), use this simplified, Pod-focused field path:
env: - name: MY_CONTAINER_NAME valueFrom: fieldRef: fieldPath: spec.containers[0].name
Full Modified Deployment Template
Here's your complete Deployment with the fix applied:
apiVersion: apps/v1 kind: Deployment metadata: creationTimestamp: null labels: run: nginx name: nginx spec: replicas: 2 selector: matchLabels: run: nginx strategy: {} template: metadata: creationTimestamp: null labels: run: nginx spec: containers: - image: nginx name: nginx ports: - containerPort: 8000 resources: {} env: - name: MY_CONTAINER_NAME valueFrom: fieldRef: fieldPath: spec.containers[0].name
Quick Tip for Multiple Containers
If you ever have multiple containers in your Pod, adjust the index in spec.containers[<index>].name to match the position of the container you want to reference. For example, the second container would use spec.containers[1].name.
内容的提问来源于stack exchange,提问作者Avi

