To pass environment variables to Kubernetes Pods, you can define them directly in your Pod or Deployment manifest, or pull them from external resources like ConfigMaps and Secrets.
1. Direct Definition
Use the env field within your container specification to define key-value pairs directly.
yaml
spec:
containers:
- name: my-container
image: nginx
env:
- name: APP_COLOR
value: "blue"
2. Using ConfigMaps (Non-Sensitive Data)
ConfigMaps allow you to decouple configuration from your image.
-
Single Key: Use
valueFromandconfigMapKeyRef. -
All Keys: Use
envFromto inject every key in a ConfigMap as an environment variable.
yaml
envFrom:
- configMapRef:
name: my-configmap
3. Using Secrets (Sensitive Data)
For passwords or API keys, use Secrets. This works similarly to ConfigMaps but provides a layer of security for sensitive data.
yaml
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: my-secret
key: password
4. Injecting Pod/Node Metadata (Downward API)
You can expose Pod information (like its IP address or the Node name it's running on) as environment variables using fieldRef.
yaml
env:
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP5. Using Command Line (kubectl)
You can quickly update environment variables for an existing Deployment or ReplicaSet without editing the YAML file manually.
-
Set variable:
kubectl set env deployment/my-deploy APP_ENV=prod -
Remove variable:
kubectl set env deployment/my-deploy APP_ENV-
Summary of Methods
| Method | Best For | Reference Field |
|---|---|---|
| Direct | Simple, static values | env |
| ConfigMap | Non-sensitive app config | configMapKeyRef or envFrom |
| Secret | Credentials/Tokens | secretKeyRef or envFrom |
| Downward API | Pod/Node metadata | fieldRef |
No comments:
Post a Comment