OneBite.Dev - Coding blog in a bite size

pass environment variables to docker

Simple docker step by step how to pass environment variables to docker with explanation

Passing environment variables to Docker is an essential skill when dealing with Docker containers. Here’s a straightforward tutorial.

Introduction

Docker allows you to define not only the system settings but also the environment your service is running in. This post will walk you through the process of passing environment variables to Docker.

Step 1: Define Environment Variables in Dockerfile

Start by defining environment variables using the ENV instruction in your Dockerfile. Assume you want to set a variable called USERNAME with a value of testuser. The syntax looks as below:

ENV USERNAME=testuser

Step 2: Set Default Values for Environment Variables

Docker allows you to set default values for any environment variables referenced in your Dockerfile that are not defined. The syntax looks as below:

ENV USERNAME=defaultuser

In this scenario, defaultuser is the default value assigned to the USERNAME environment variable in the absence of specified value for USERNAME.

Step 3: Override Environment Variables

Remember, environment variables defined using the docker run -e or --env flag will override those defined in the Dockerfile. If you wanted to override the USERNAME environment variable defined earlier, the syntax would appear as below:

docker run -e "USERNAME=myuser" myimage

Here, myuser is the new value assigned to the USERNAME variable, and myimage is the Docker image you’re running.

Step 4: Use.env File

Environment variables can also be set using a .env file. This method is useful, especially when dealing with numerous variables. Just create a file named .env, and add your variables like so:

USERNAME=myuser
PASSWORD=mypassword

Instruct Docker to read from the .env file using --env-file flag as shown:

docker run --env-file .env myimage

Step 5: Use Docker-Compose

If you’re using Docker-Compose, you can define environment variables in your docker-compose.yml file. The environment section allows you to set any environment variables as shown below:

services:
  myservice:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      USERNAME: myuser

Conclusion

And there you have it! You now know how to pass environment variables to your Docker container. Environment variables are a powerful way to configure your Docker container. Now, go forth and use them wisely!

docker