[SOLVED] docker-compose does not create none-existing variable in .env file

Issue

This Content is from Stack Overflow. Question asked by Mwthreex

This is a setup for laravel project:

Dockerfile:

FROM php:8.1.2-cli-buster

COPY --from=composer /usr/bin/composer /usr/bin/composer

RUN apt-get update && apt install git -y

WORKDIR /var/www/html

COPY . .

RUN composer install --no-dev

RUN mv ./.env.example .env

RUN php artisan key:generate

CMD ["/bin/bash", "-c", "php artisan serve --host 0.0.0.0 --port 8000"]

Look at this variable inside docker-compse.yml

version: "3.8"

services:
  artisan:
    build: .
    environment:
        CUSTOM_VAR: custom-value-from-compse

    ports:
      - '8000:8000'

api.php

Route::get('test', function () {
    dump(env('CUSTOM_VAR')); //CUSTOM_VAR is null
});

The above route should dump custom-value-from-compse value but it dumpnull, What is the problem here ? It only overide existing variable in .env file, I mean if i set CUSTOM_VAR in .env file to ‘some-value’ it does not override it to the value inside of the docker compose

Note: the CUSTOM_VAR wil be null even i put it in Dockerfile…



Solution

Maybe try this:

version: "3.8"

services:
  artisan:
    build: .
    environment:
      # laravel uses Dotenv to set and load environment variables,by default it will not
      # overwrite existing environment variables. So we set env variables for app container here
      # then laravel will use these env values instead of the same env variables  defined in .env file.
      - "CUSTOM_VAR=custom-value-from-compse"

    ports:
      - '8000:8000'

Source: https://gist.github.com/kevinyan815/fa0760902d29f19a4213b4a16fe0501b#file-docker-compose-yml-for-laravel-L11


This Question was asked in StackOverflow by Mwthreex and Answered by Markus It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?