Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker compose, link file outside container

I'm working with docker-compose for a laravel project and nginx.

This is my docker-compose.yml :

version: '2'
services:
  backend:
    image: my_image
    depends_on:
     - elastic
     - mysql
  mysql:
    image: mysql:8.0.0
  nginx:
    depends_on:
     - backend
    image: my_image
    ports:
      - 81:80

So, my Laravel project is in the container backend, and If I run the command : docker-compose up -d it's ok, all containers are created and my project is running on port 81.

My problem is, In the Laravel project in my container backend, I have a .env file with database login, password and other stuff.

How can I edit this file after docker-compose up ? Directly in the container is not a good idea, is there a way to link a file outside a container with docker-compose ?

Thanks

like image 534
Clément Andraud Avatar asked Mar 30 '26 00:03

Clément Andraud


1 Answers

One approach to this is to use the 'env_file' directive on the docker-compose.yml, in there you can put a list of key value pairs that will be exported into the container. For example:

web:
    image: nginx:latest
    env_file:
        - .env
    ports:
        - "8181:80"
    volumes:
        - ./code:/code

Then you can configure your application to use these env values.
One catch with this approach is that you need to recreate the containers if you change any value or add a new one (docker-compose down && docker-compose up -d).

like image 89
Marcos Pagnucco Avatar answered Apr 02 '26 21:04

Marcos Pagnucco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!