How to assign an environment variable to a container?

we can pass environment variables also in YAML file using the environment tag as shown below.

version: "3"
services:
  web:
    build: .
    ports:
      - "5000:5000"
    environment:
      - Name=Gaurav
      - Add=Rajasthan
  redis:
    image: "redis:alpine"

Let's rerun the compose file to check if the environment variable is updated or not inside the container.

gaurav@learning-ocean:~$ docker-compose up -d
Creating network "docker-env_default" with the default driver
Creating docker-env_redis_1 ... done
Creating docker-env_web_1   ... done

Docker-compose exec <container_name> env is the command to check the environment variable in any container.

gaurav@learning-ocean:~$ docker-compose exec web env
PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=226286f7d3fd
TERM=xterm
Name=Gaurav
Add=Rajasthan
LANG=C.UTF-8
GPG_KEY=97FC712E4C024BBEA48A61ED3A5CA953F73C700D
PYTHON_VERSION=3.4.10
PYTHON_PIP_VERSION=19.0.3
HOME=/root
gaurav@learning-ocean:~$

Now, let’s suppose there are 50 environment variables in one container, it is very difficult to write all 50 variables in the YAML file and it will make the YAML file lengthy, So to overcome this problem we can define all environment variables in a file called env.txt.

so env.txt file contains below

Name=Gaurav
ADD=Jaipur

We have to modify the docker-compose yaml file by adding tag env_file ,So that all the environment variables will get added in the container. We can give multiple env.txt files.

version: "3"
services:
  web:
    build: .
    ports:
      - "5000:5000"
    env_file:
      - .env.txt
  redis:
    image: "redis:alpine"

Rerun the YAML file docker-compose up -d and you will see using exec command that variables which were defined in env.txt file will get add-in container.

gaurav@learning-ocean:~$ docker-compose exec web env
PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=226286f7d3fd
TERM=xterm
Name=Gaurav
Add=Jaipur
LANG=C.UTF-8
GPG_KEY=97FC712E4C024BBEA48A61ED3A5CA953F73C700D
PYTHON_VERSION=3.4.10
PYTHON_PIP_VERSION=19.0.3
HOME=/root
gaurav@learning-ocean:~$

.env file variable also present in docker-compose by default. Users can also define the .env file to make compose file more generic. In .env file versions of application also could be mention as shown below.

PYTHON_VERSION=3.4
REDIS_IMAGE=redis:alpine

In Dockerfile, modify the args tag as shown below and args will read the PYTHON_VERSION from the .env file

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - PYTHON_VERSION=${PYTHON_VERSION}
    image: python-redis-1
    ports:
     - "5000:5000"
  redis:
    image: ${REDIS_IMAGE}