When you create a Pod, you can set environment variables for the containers that run in the Pod.
To set environment variables, include the env or envFrom field in the configuration file.
Note: The environment variables set using the env or envFrom field will override any environment variables specified in the container image.
Example:
Create a Pod that runs one container.
The configuration file for the Pod defines an environment variable with name DEMO_GREETING and value "Hello from the environment".
Here is the configuration file for the Pod:
pods/inject/envars.yaml
apiVersion: v1
kind: Pod
metadata:
name: envar-demo
labels:
purpose: demonstrate-envars
spec:
containers:
- name: envar-demo-container
image: gcr.io/google-samples/node-hello:1.0
env:
- name: DEMO_GREETING
value: "Hello from the environment"
- name: DEMO_FAREWELL
value: "Such a sweet sorrow"
-
Create a Pod based on the YAML configuration file:
kubectl apply -f https://k8s.io/examples/pods/inject/envars.yaml
-
List the running Pods:
kubectl get pods -l purpose=demonstrate-envars
The output is similar to this:
NAME READY STATUS RESTARTS AGE
envar-demo 1/1 Running 0 9s
-
Get a shell to the container running in your Pod:
kubectl exec -it envar-demo -- /bin/bash
-
In your shell, run the printenv command to list the environment variables.
root@envar-demo:/# printenv
The output is similar to this:
NODE_VERSION=4.4.2
EXAMPLE_SERVICE_PORT_8080_TCP_ADDR=10.3.245.237
HOSTNAME=envar-demo
...
DEMO_GREETING=Hello from the environment
DEMO_FAREWELL=Such a sweet sorrow
-
To exit the shell, enter exit.