skip to Main Content

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…

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can set default values for variables in docker-compose file. If variables in .env file doesn’t exist the default value will be set, otherwise it will be override it to the value inside of the docker compose.

    version: "3.8"
    services:
      artisan:
        build: .
        environment:
            - CUSTOM_VAR=${CUSTOM_VAR_FROM_ENV_FILE:-custom-value-from-compse}
    

    https://docs.docker.com/compose/environment-variables/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search