Set docker compose ARGS from an env file

Viewed 343

I have a Dockerfile and a docker-compose.yml file. For both, I want to use the .env.local env file

Here is the file tree:

|-- .env
|-- .env.local
|-- docker
|   |-- Dockerfile
|   |-- docker-compose.yml

Here is the command to build the image:

docker-compose -f docker/docker-compose.yml build

I want to pass the proxy values existing in my .env.local to the Dockerfile Here are the content of every file.

> cat .env
HTTP_PROXY=127.27.0.1:8080
HTTPS_PROXY=127.27.0.1:8080
> cat .env.local
HTTP_PROXY=127.0.0.1:9090
HTTPS_PROXY=127.0.0.1:9090
> cat docker/docker-compose.yml
version: '3.5'
services:
  web:
    env_file:
      - ../.env.local
    build:
      context: ../
      dockerfile: docker/Dockerfile
      args:
        - HTTP_PROXY
        - HTTPS_PROXY
> cat docker/Dockerfile
FROM php:8.1-fpm-bullseye

RUN usermod -u 1000 www-data

ARG HTTP_PROXY
ARG HTTPS_PROXY

ENV http_proxy=${HTTP_PROXY}
ENV https_proxy=${HTTPS_PROXY}

RUN printenv

There is a command in my Dockerfile that prints the env vars, The values are taken from the .env file instead of .env.local

How can I correct that ?

1 Answers

With the env_file option, docker compose injects enviromental variables to the running container.

As a result when you run printenv, in the build phase you do not get the result you expected.

If you want to pass environmental variables to the build phase, I would recommend removing the env_file option

Instead, run

source .env.local

The variables are now available to your bash as enviromental variables

Then run the following build command

docker-compose build --build-arg HTTP_PROXY=$HTTP_PROXY --build-arg HTTPS_PROXY=$HTTPS_PROXY

Now compose knows their values at the build phase and can be passed to your docker build.

docker-compose.yml

version: '3.5'
services:
  web:
    build:
      context: ../
      dockerfile: docker/Dockerfile
      args:
        - HTTP_PROXY
        - HTTPS_PROXY
Related