How to pass environment variables to Docker containers

In the world of containerization, Docker has become the industry standard for packaging applications and their dependencies. One critical aspect of configuring your Dockerized application is managing environment variables. In this blog, we will explore different methods to pass environment variables to Docker containers.

Different Ways to Pass Environment Variables

1. Dockerfile ENV Instruction

In your Dockerfile, you can use the ENV instruction to set environment variables:

ENV DATABASE_URL=mysql://user:password@localhost:3306/mydb

While building docker image you can specify the ENV.

2. Docker Run -e Option

When you run a Docker container using the docker run command, you can use the -e or --env option to set environment variables:

docker run -e DATABASE_URL=mysql://user:password@localhost:3306/mydb myapp

This method allows you to override any environment variables set in the Dockerfile.

3. Docker Compose Environment Section

If you use Docker Compose to manage multi-container Docker applications, you can specify environment variables in your docker-compose.yml file:

version: '3'
services:
  myapp:
    image: myapp-image
    environment:
      - DATABASE_URL=mysql://user:password@db:3306/mydb
  db:
    image: mysql
    environment:
      - MYSQL_ROOT_PASSWORD=rootpassword
      - MYSQL_DATABASE=mydb

4. Using .env Files

Docker supports using .env files to load environment variables into containers. This feature simplifies container configuration and allows for more flexible application behavior. Here’s how to use .env files with Docker:

Create a .env File: Start by creating a .env file in your project directory. Add your key-value pairs, one per line. For example

DATABASE_URL=mysql://user:password@localhost:3306/mydb
API_KEY=your-secret-key
DEBUG=true

Load the .env File: To load the .env file when running a container, use the --env-file option with the docker run command:

docker run --env-file .env myapp

Environment variables are a fundamental aspect of configuring Docker containers. They provide a flexible way to manage configuration without changing your application code. In this blog, we’ve explored various methods to pass environment variables to Docker containers. The method you choose depends on your specific use case and the tools you use to manage your containerized applications.

Related Post