Environmental File for Variables
Learning objectives
- Knows how to use environmental variables for application configuration.
When we look at the docker-compose.yml
file, it contains passwords and other information one typically does not wish to include in the configuration file. One of the main reasons for this is that the configuration may differ between servers -- one could, for example, have a separate configuration for development and production.
Development and production
In practice, one can also also use separate Dockerfiles for development and production environment, or -- for example -- use additional configurations for the production environment. For more details, check out Using compose in production. Check out also Docker Development Best Practices.
At the very basic level, even if one would not have separate Dockerfiles or Docker compose files for development and production, it is still meaningful to extract configurations to a separate file, which can then be changed depending on the environment. To achieve this, let's create a file called database.env
and add it to the same folder with the docker-compose.yml
file. Let's set the contents of the file as follows.
PGPORT=5432
PGDATABASE=database
PGUSER=username
PGPASSWORD=password
PGHOST=postgres-database
POSTGRES_USER=username
POSTGRES_PASSWORD=password
POSTGRES_DB=database
FLYWAY_USER=username
FLYWAY_PASSWORD=password
FLYWAY_URL=jdbc:postgresql://postgres-database:5432/database
Next, we change the docker-compose.yml
file so that instead of the environmental variables, it uses the file that we created above. With the change, the docker-compose.yml
looks as follows.
version: "3.4"
services:
app:
build: .
restart: unless-stopped
volumes:
- ./:/app
ports:
- 7777:7777
depends_on:
- database
env_file:
- database.env
database:
container_name: "postgres-database"
image: "postgres:13.4"
restart: unless-stopped
env_file:
- database.env
flyway:
image: flyway/flyway:7.3.0-alpine
env_file:
- database.env
depends_on:
- database
volumes:
- .:/flyway/sql
command: -connectRetries=60 -baselineOnMigrate=true migrate
The application should still continue to run as expected. The full structure of the project is as follows.
tree --dirsfirst
.
├── flyway
│ └── sql
│ ├── V1__initial_database.sql
│ └── V2__phone_numbers.sql
├── app.js
├── database.env
├── docker-compose.yml
└── Dockerfile
Using environmental variables
Note that the environmental variables are presently automatically taken into use by the libraries that we use. In Deno applications, we can also access environmental variables through Deno.env
. As an example, if we would wish to log the value of the PGHOST
environmental value, we would use.
console.log(Deno.env.get("PGHOST"));