Load .env File When Running Docker Image
Docker has built-in support for environment (.env) files. This is a handy way to manage configuration settings that must be passed into containers during runtime, such as API keys, database passwords, and other sensitive or customizable data.
- Create a file named
.envin your project directory. - Add environment variables in the format
KEY=valueon separate lines. For example:
DATABASE_HOST=localhost DATABASE_USER=root DATABASE_PASS=secret
Use the --env-file option when running your Docker container. This option lets you specify the path to your .env file, which Docker will read and set the environment variables from within the container. It looks like this:
docker run --env-file ./.env your-image-name
This command tells Docker to load the environment variables defined in the .env file into the container at runtime.
