Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AlexanderKim's avatar

How to use docker compose's env variables inside laravel/lumen envs?

If i set env variables inside compose.yml:

version: '3'
services:
  branch-api:
    restart: always
    image: "imagename"
    ports:
      - 9000:80
    container_name: "branch"
    environment:
      - "DB_CONNECTION=pgsql"
      - "DB_HOST=152.1.1.1"
      - "DB_PORT=5432"
      - "DB_DATABASE=branch"
      - "DB_USERNAME=branch"
      - "DB_PASSOWRD=branch"

How do i use compose env variables inside laravel/lumen .env file? For example:


DB_CONNECTION=env('DB_CONNECTION')

But that won't work.

0 likes
5 replies
bobbybouwmann's avatar

You can just use the env helper method in your code for that. You don't have to add them to the .env file as well because the container already has these variables available. You can just use them right away ;)

// In your code somewhere

$host = env('DB_HOST');
AlexanderKim's avatar

@bobbybouwmann i have these variables at container layer, but my .env (file) has no defined variables, so it cannot connect to a database.

bobbybouwmann's avatar

Well the env helper will read first the variables that are on the server/container and then the .env file itself. So it should be available for you!

Your syntax also seem to be incorrect, try this

environment:
    - DB_CONNECTION: "pgsql"
    - DB_HOST: "152.1.1.1"
    - DB_PORT: "5432"
    - DB_DATABASE: "branch"
    - DB_USERNAME: "branch"
bobbybouwmann's avatar

Mmh that is odd... Have you tried my example? I have it like that in my docker-compose.yml file!

Please or to participate in this conversation.