1

To demonstrating the issue, I setup a sample laravel app in a dockerfile which uses php built-in server:

FROM composer:latest

WORKDIR /var/www/html

RUN composer create-project laravel/laravel . --no-dev

RUN mv ./.env.example .env

RUN php artisan key:generate

RUN echo "<?php Route::get('test', fn() => dump(getenv('MY_ENV')));" > routes/api.php

CMD php artisan serve --host 0.0.0.0

As you can see i added a route to simply dump the MY_ENV variable which defined in docker-compose.yml file:

version: "3.8"

services: 
  laravel:
    build: .
    tty: true
    ports:
      - '8000:8000'
    environment:
      MY_ENV: 123

And: docker compose up -d then head over to localhost:8000/api/test.

As you can see getenv return false but i expected it to be 123

The interesting part is, When i use laravel tinker the variable is available :

enter image description here

But this variable is not available in the actual app, What would be the problem here?

Mwthreex
  • 913
  • 1
  • 11
  • 24

1 Answers1

0

From what I know, the docker compose environment it's not for build the image.

If you want to pass the argument to the dockerfile throught the docker-cmpose.yml you need to use this

version: "3.8"

services: 
  laravel:
    build: .
      args:
        MY_ENV: 123
    tty: true
    ports:
      - '8000:8000'
    environment:
      MY_ENV: 123

And in the dockerfile you setup the ARG MY_ENV to use it, like this:


ARG MY_ENV
FROM composer:latest

WORKDIR /var/www/html

RUN composer create-project laravel/laravel . --no-dev

RUN mv ./.env.example .env

RUN php artisan key:generate

RUN echo "<?php Route::get('test', fn() => dump($buildno));" > routes/api.php

CMD php artisan serve --host 0.0.0.0

Reference: How to define build args in docker compose

  • Thanks, But the weird issue is, When i use ngnix as web server, It read the `environment` variables. – Mwthreex Oct 01 '22 at 13:42
  • ARG is fine, But i need to use ENV variables because i need to override .env variables file – Mwthreex Oct 01 '22 at 13:43
  • @Mwthreex When you said that ngnix it read the environment, is it after the build of image? Because what I think is that you can't using env during building image, because it's docker and not the ngnix server running. – luca-rigutti Oct 02 '22 at 09:36
  • the `CMD` instructor is not execute in the build time, Doesn't it ? Because i boot up web server with CMD in last line of dockerfile. – Mwthreex Oct 02 '22 at 11:10
  • @Mwthreex from the documentation of docker `Do not confuse RUN with CMD. RUN actually runs a command and commits the result; CMD does not execute anything at build time, but specifies the intended command for the image.` https://docs.docker.com/engine/reference/builder/#cmd So the server isn't running until the image is created, then you can access to env file. – luca-rigutti Oct 02 '22 at 12:20