Documentation for Kubernetes v1.11 is no longer actively maintained. The version you are currently viewing is a static snapshot. For up-to-date documentation, see the latest version.

Edit This Page

Define Environment Variables for a Container

This page shows how to define environment variables for a container in a Kubernetes Pod.

Before you begin

You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using Minikube, or you can use one of these Kubernetes playgrounds:

To check the version, enter kubectl version.

Define an environment variable for a container

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.

In this exercise, you 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:

envars.yaml docs/tasks/inject-data-application
apiVersion: v1
kind: Pod
  name: envar-demo
    purpose: demonstrate-envars
  - name: envar-demo-container
    image: gcr.io/google-samples/node-hello:1.0
    - name: DEMO_GREETING
      value: "Hello from the environment"
    - name: DEMO_FAREWELL
      value: "Such a sweet sorrow"
  1. Create a Pod based on the YAML configuration file:

    kubectl create -f https://k8s.io/docs/tasks/inject-data-application/envars.yaml
  2. 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
  3. Get a shell to the container running in your Pod:

    kubectl exec -it envar-demo -- /bin/bash
  4. In your shell, run the printenv command to list the environment variables.

    root@envar-demo:/# printenv

    The output is similar to this:

    DEMO_GREETING=Hello from the environment
    DEMO_FAREWELL=Such a sweet sorrow
  5. To exit the shell, enter exit.

Note: The environment variables set using the env or envFrom field will override any environment variables specified in the container image.

What's next


Create an Issue Edit this Page