Skip to content
Advertisement

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement