Skip to main content

One post tagged with "devops"

View All Tags

· 2 min read

How to Pass Environment Variables to Docker Containers

Passing environment variables at runtime allows for greater flexibility and customization of container behavior without the need to modify the Docker image. This flexibility is particularly useful when deploying the same image in different environments or when making quick adjustments to configurations.

Sensitive information, such as API keys or database credentials, is often stored in environment variables. Passing these variables at runtime enhances security by avoiding the inclusion of sensitive data in the Docker image. This approach helps protect sensitive information and prevents accidental exposure.

Prerequisites

Before we begin, ensure that you have Docker desktop installed on your system.

Creating a Basic Docker Image

Let's start by creating a basic Docker image that echoes "hello world" to the terminal. We'll use an environment variable named NAME to customize the output.

Create a file named Dockerfile with the following content:

FROM alpine
ENV NAME=world
CMD ["/bin/sh", "-c", "echo hello $NAME"]

This Dockerfile sets the NAME environment variable to "world" and prints "hello" followed by the value of NAME when the container runs.

Build the Docker image with the following command:

docker build -t hello-world .

Now, run the Docker container:

docker run hello-world

You should see the output:

hello world

Suppose now if you want to change the output form hello world to something else like hello anukul , you don't have to build the image again and then run container, you can simply

Pass the env flag to change env variable on runtime

docker run --env NAME=anukul hello-world

You should see the output:

hello anukul

Conclusion

In this guide, we've covered a basic example of passing environment variables to Docker containers. This simple approach allows you to customize the behavior of your containers based on the values of environment variables.