Malathi
Malathi

Reputation: 2195

Docker compose env variable not substituted

I have my docker-compose setup like this

docker-compose.yml:

version: '3.9'
services:
  busybox:
    image: busybox:latest
    environment:
      - DB_HOST=${DB_HOST}
    env_file:
      - test.properties

test.properties:

DB_URL=jdbc://mysql://${DB_HOST}:app_db

.env:

DB_HOST=localhost

when I run docker-compose config command, the output is like this,

services:
  busybox:
    environment:
      DB_HOST: localhost
      DB_URL: jdbc://mysql://:app_db
    image: busybox:latest
version: '3.9'

As you see, the environment variable DB_HOST is defined as 'localhost' in the .env file but the variable is set to '' by docker-compose in the environment variable 'DB_HOST' and is showing as jdbc://mysql://:app_db. But I want the value of DB_HOST like this DB_HOST: jdbc://mysql://localhost:app_db. How could I achieve this?

My docker and docker-compose version looks like this

> docker -v
Docker version 20.10.5, build 55c4c88

> docker-compose version
docker-compose version 1.28.5, build c4eb3a1f
docker-py version: 4.4.4
CPython version: 3.9.0
OpenSSL version: OpenSSL 1.1.1h  22 Sep 2020

The workaround as suggested by antonio-petricca is working, but I want to know if anybody happens to solve the issue without setting the env variable before running docker-compose up? This used to work earlier with the older versions of docker-compose, but with some updates, it stopped working. I am not sure it's broken on which docker-compose version.

Upvotes: 2

Views: 1993

Answers (2)

Oceania Water
Oceania Water

Reputation: 327

Maybe another workaround is to add DB_HOST to your test.properties file?

DB_HOST=${DB_HOST:-localhost}
DB_URL=jdbc://mysql://${DB_HOST}:app_db

However, you still have to keep .env for

environment:
  - DB_HOST=${DB_HOST}

So you have to make sure the values are the same at both settings...not sure if it is a better solution.

Upvotes: 0

Antonio Petricca
Antonio Petricca

Reputation: 10996

I had the same issue some time ago, and workaround was:

#!/bin/bash

DB_HOST=localhost

DB_HOST=${DB_HOST} docker-compose # ... command arguments ...

You can repeat the same for other variables.

Tell me if that works for you.

Regards.

Upvotes: 1

Related Questions