12 Secrets and .env
Tim Svensson edited this page 2026-04-27 10:26:28 +00:00

.env file

  • An .env file is used to store sensitive data e.g credentials using environment variables instead of hardcoding them directly in the code.

Why use .env file

We use an .env file to separate configuration values from the code.

  • This keeps sensitive data out of the code.
  • It improves security since the values are not pushed to the repository.
  • It allows for flexibility as values can be updated without changing the code.

When to use .env file

  • An .env file can be used when working with credentials or other sensitive data.
    • We currently use it for MQTT and all Postgres databases.
  • It's also useful when values need to change between different environments, e.g when each developer uses their own local configuration.

How it works

  1. Values are stored in .env file.
  2. The compose.yaml file uses environment variable references that are replaced with values from the .env file. Docker Compose documentation
  3. The services get the values from the environment using Environment.GetEnvironmentVariable.

It is extremly important that the .env is never included in a commit! Do NOT remove it from the .gitignore!

Create .env file

The .env file is generated automatically by the installation scripts (README) and is placed in the same directory as the compose file. The .env file will only be generated if it doesn't currently exist, so if new values are added by another branch you will need to delete it manually to receive new fields.

An example of how the .env file might look like:

DATABASE_USER=120153063346022930723500 
DATABASE_PASSWORD=2965047416668206777197 

Docker Compose

The variables are set in compose.yaml and used by the services:

environment:
      DATABASE_USER: ${DATABASE_USER}
      DATABASE_PASSWORD: ${DATABASE_PASSWORD}

Using environment variables

Values are read using Environment.GetEnvironmentVariable:

Environment.GetEnvironmentVariable("DATABASE_USER"); 
Environment.GetEnvironmentVariable("DATABASE_PASSWORD");