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...
CodePudding user response:
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'
CodePudding user response:
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}