Roukmoute
Roukmoute

Reputation: 779

Overriding environment values via .env.local

By default we can set default values in an environment file named .env.

I would like to know if there is a simple way to use a .env.local for example to override an environment value.

I know I can use docker-compose.override.yaml but the key env_file must be in all containers:

version: '3.5'
services:
  php:
    env_file:
      - ./.env.local
  nginx:
    env_file:
      - ./.env.local

But this is not really a elegant way because I use a file (docker-compose.override.yaml) to tell it to use this file (./.env.local).

Another things of course is to fullfill docker-compose.override.yaml with directly values:

version: '3.5'
services:
  php:
    build:
      args:
        HTTP_PROXY: ''
        NO_PROXY: ''
    environment:
      XDEBUG: 1
  nginx:
    build:
      args:
        UPSTREAM: 'php:9000'

This works really well but it is not really an easiest way to override keys for anyone has just beginning in Docker.

Have you an idea to have a simple way like .env for overriding value?

Upvotes: 2

Views: 5253

Answers (2)

kunashir
kunashir

Reputation: 949

I posted my solution because it can be useful for someone. Docker-compose.yml allows you to specify the env_file key for service. And it can be an array, so you can use two (or more) files, and if these files have the same variables values will be used from the last one:

version: '3'

services:
  app: &app
    build:
      context: .
    tmpfs:
      - /tmp
    env_file:
      - .env.development
      - .env.development.local

Upvotes: 3

Adrian Soomro
Adrian Soomro

Reputation: 46

There is a way to do this by using the --env-file <path to env file> option for docker-compose

Eg: To demonstrate what I mean, I put together a small demo,

I've made a docker-compose file with 1 service - test that builds an image from alpine and instructs the container to printenv when it starts.

file structure

Then I went ahead and ran this, first with no --env-file to demonstrate that by default docker-compose picks up values in .env file, then with the --env-file option to demonstrate the override.

using --env-file

Upvotes: 1

Related Questions