Environment Variables with Docker-compose

Currently, we have included our database credentials in the code itself. But in production systems and an ideal development workflow, it is not advised to add such critical information in the code.

Clone the project using git clone https://github.com/venky8283/Docker.git

Type git checkout 6e24a37faa2e1bd3401c77b2951f995f410b3d35 to get to the code used in the lesson.

Environment variables are one of the options that are used in production systems to manage credentials. So, let’s see how to work with the environment variables using Docker.

Accessing environment variables in Docker

Using the .env file

A file with only the .env extension is used in the production systems to store all the variables. Since it is a hidden file, it is not normally pushed to the code.

We will create a .env file and move the variables to the .env file. To access the variables, we will use ${} syntax in docker-compose.

The .env file should be in the same folder where the docker-compose.yml file is located.

You can try running docker-compose up once these changes are done.

Get hands-on with 1400+ tech skills courses.