Docker how to read values from an .env file

Sami Samiuddin
Jul 16, 2024

--

There’s an easy way to read info from env file.

It’s quite useful when you don’t want to pass info via CLI or hard code the it in Dockerfile or compose.yaml.

Basically create an .env file in root of your project near compose.yaml

Example of .env:

DB_CONNECTION=mysql
DB_PASSWORD=p4ssword
DB_HOST=sixthdesk-mysql-1
DB_PORT=3306
DB_DATABASE=sixthdesk
DB_USERNAME=root

And finally within compose.yaml you can read the value from file like so:


services:
mysql:
image: mysql
ports:
- "3306:3306"
networks:
- my-network
environment:
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
volumes:
- mysql_docker_host:/var/lib/mysql

backend:
image: verax5/sixthdesk
ports:
- "8000:8000"
networks:
- my-network
volumes:
- type: bind
source: ~/Sites/sixthdesk
target: /var/www/html
networks:
my-network: {}

volumes:
mysql_docker_host: {}

You can now run docker compose up to execute compose.yaml and the values will be available to use!

Note I’m using docker 24.

--

--

Sami Samiuddin
Sami Samiuddin

No responses yet