Search code examples
phpdockerdocker-compose

Share environment variables between two containers from docker-compose


In docker compose, I have two containers, one named php-container, the other nginx. For the NGINX container, I defined an environment variable.
Is there a way to access that variable in the PHP container? I want to access the PLAYER_NAME variable in my PHP container

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

Solution

  • 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