Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

share env variables between 2 containers from docker-compose

In my docker-compose, I have 2 containers, php-container, and nginx container. For nginx container I defined env variable, is there a way to access that variable in php container in code? I want to access in php code the PLAYER_NAME variable

version: '3.7'

services:
  api:
    build: '.'
    volumes:
      - './:/srv/api:rw'
    env_file:
      - .env
    networks:
      - backend

  nginx_player_1:
    image: 'nginx:1.15.7-alpine'
    depends_on:
      - api
    volumes:
      - './docker/nginx/conf.d:/etc/nginx/conf.d:ro'
      - './:/srv/api:rw'
    ports:
      - '8001:80'
    environment:
      PLAYER_NAME: 'PLAYER_1'
    networks:
      - backend
like image 851
Andrei Nt Avatar asked Feb 03 '19 12:02

Andrei Nt


People also ask

Does Docker compose override environment variables?

But docker-compose does not stop at the . env and the host's current environment variables. It's cool that you can simply override values of your . env file, but this flexibility is can also be the source of nasty bugs.

How do you pass variables from Docker Compose to Dockerfile?

Pass variables into Dockerfile through Docker Compose during build. If you want to pass variables through the docker-compose process into any of the Dockerfiles present within docker-compose. yml , use the --build-arg parameter for each argument to flow into all of the Dockerfiles.


1 Answers

Nope, you cannot do that, containers are isolated by design. You have to define the env variable for both containers.

To not duplicate your code, you can use either yaml anchors with extension fields:

version: '3.7'

x-environment: &commonEnvironment
    PLAYER_NAME: 'PLAYER_1'

services:
    service-1: 
        environment: *commonEnvironment
    service-2: 
        environment: *commonEnvironment

or you can use env-file. Where you put all your variables in file, and reference it from docker-compose using env_file

like image 184
michalhosna Avatar answered Sep 20 '22 18:09

michalhosna