Retrieve current environment in code (Kotlin, Docker) Retrieve current environment in code (Kotlin, Docker) docker docker

Retrieve current environment in code (Kotlin, Docker)


Just pass it as environment variable (e.g. APP_ENV) to you app and use System.getenv("APP_ENV") to access it. It's one of the twelve-factor app best practices, btw.

The way you pass to you container differs depending on the way you start it.

Docker run

Pass the variables directly via --env / -e options for docker run command, or store them in a file and pass the whole file via --env-file:

docker run -e VAR1 --env APP_ENV=dev --env-file ./env your_image:latest

Docker compose

Use environment or env_file (note that they set NODE_ENV variable in the docs, just like in your case!):

version: '3'services:  app:    image: 'your_image:latest'    env_file:     - ./env    environment:     - APP_ENV=dev

Kubernetes

Use env:

spec:  containers:  - name: app    image: your_app:latest    env:    - name: APP_ENV      value: "dev"

In k8s you can reference another values in environment variables, so the environment can be stored in the metadata.


There are, of course, other ways to provide values to the app, like:

  • Code generation and build-time substitutions. It can be used to provide, for example, Git revision: the output of git rev-parse is just substituted somewhere in your code. Requires extra build configuration + you'll need different builds for different envs.
  • Program arguments. It's as simple as running app arg1 arg2 ... dev ... argn. Pretty similar to environment variables, but, IMHO, has a flaw: program args are accessible only in your program's entry point (main), so you'll need to parse them and pass to the other parts of the app. I can be good for some dynamic inputs, but inconvenient for a static data, like app's environment.
  • Vendor metadata, like EC2 Instance Metadata and User Data. Requires specific APIs to access.

As you see none of them provides a combination of flexibility, ubiquity and simpleness of environment variables.