How to Set Docker Environment Variables

Docker’s versatility extends beyond just packaging applications; it empowers developers to create dynamic and configurable containers. One key feature for achieving this configurability is the use of environment variables. In this blog post, we’ll explore how to leverage environment variables in Docker, using the popular BusyBox image as an example.

Understanding Environment Variables in Docker

Environment variables in Docker serve as dynamic values that can be passed to containers during runtime. They are a means of configuring applications and adjusting their behavior without modifying the container’s code.

Let’s dive into a practical example using the lightweight BusyBox image.

Step 1: Create a Simple Dockerfile

Start by creating a Dockerfile. For simplicity, we’ll use BusyBox, a minimalistic yet powerful base image.

# Use BusyBox as the base image
FROM busybox

# Set an environment variable
ENV MY_VARIABLE=my_value

# Command to run upon container start
CMD echo "The value of MY_VARIABLE is $MY_VARIABLE"

In this example, we set an environment variable named MY_VARIABLE with the value my_value.

Step 2: Build the Docker Image

Navigate to the directory containing your Dockerfile and execute the following command to build the Docker image:

docker build -t my-busybox-app .

This command instructs Docker to build an image named my-busybox-app using the specified Dockerfile.

Step 3: Run the Docker Container

Now that the image is built, let’s run a container based on it:

docker run my-busybox-app

Upon execution, the container prints the value of MY_VARIABLE to the console. In this case, it will output:

The value of MY_VARIABLE is my_value

Step 4: Overriding Environment Variables

One of the strengths of using environment variables is the ability to override them during runtime. Let’s explore this by running the container with a different value for MY_VARIABLE:

docker run -e MY_VARIABLE=custom_value my-busybox-app

This time, the container will output:

The value of MY_VARIABLE is custom_value

The -e flag allows us to set the environment variable MY_VARIABLE to a new value, effectively overriding the default.

Conclusion

Congratulations! You’ve just scratched the surface of harnessing the power of environment variables in Docker. This simple example using BusyBox illustrates how environment variables can make your containers more flexible and configurable.

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم