DEV Community

Cover image for Set environment variables in docker
Hari Kotha
Hari Kotha

Posted on

Set environment variables in docker

How to use Env variables in Docker & docker-compose


Dockerfile

1. ENV

Use ENV command to set env variable in Dockerfile.

ENV username=barryallen
echo $username // barryallen

# Build this image and run it as a container
docker build -t docker-env .

docker run docker-env
# logs "barryallen"
Enter fullscreen mode Exit fullscreen mode

Environment variables defined with ENV command are persisted in multiple containers running the same image. These can be overridden using run command with -e flag.

# Use -e or --env to override env variables in Dockerfile via build command
docker run -e/--env "username=clark kent" docker-env

# Use --env-file to use .env file to override env variables in Dockerfile
docker run --env-file .env docker-env
Enter fullscreen mode Exit fullscreen mode

Use this to override a variables in a specific container. Other containers running without -e flag still uses env variable defined in Dockerfile

2. ARG

Use ARG command to use dynamic values that are only necessary while building the image and not needed while running it as container

ARG location="Gotham City"

echo $location // Gotham City

# build the image & run in container
docker build -t docker-env .

docker run docker-env
# location will not be available as ENV variable in containers
Enter fullscreen mode Exit fullscreen mode

This ARG variable can be dynamically passed in build command as 👇

docker build -t app-latest --build-arg "location=Watch Tower"
Enter fullscreen mode Exit fullscreen mode

3. Use ARG as ENV

We can persist ARG variables by mapping them to ENV variables in Dockerfile.

ARG version
ENV VERSION=${version}
echo $VERSION

docker build -t docker-env . --build-arg "version=1.0.1"

docker run docker-env
# 1.0.1

Enter fullscreen mode Exit fullscreen mode

docker-compose

1. environment

docker-env:
    build:
        context: ./
    environment:
        - VERSION=1.0.0
Enter fullscreen mode Exit fullscreen mode

You can set environment variables in a service’s containers with the environment attribute in your Compose file.

This works the same way as docker run -e VARIABLE=VALUE docker-image

2. env_file

docker-env:
    build:
        context: ./
    env_file: .env
Enter fullscreen mode Exit fullscreen mode

Instead of hardcoding env variables in your compose file, you can add those keys in a .env file and provide it to env_file attribute.

This works the same way as docker run --env-file=FILE docker-image

When both env_file and environment are set for a service, values set by environment have precedence.


Thanks for reading!

cheers :)

Checkout my other blogs

Top comments (0)