Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve current environment in code (Kotlin, Docker)

Tags:

docker

kotlin

I would like to retrieve info about where the application is running.

So let's say I have a DEV and PROD environment. In my code, I would like to retrieve the link of the environment, where the application is running, e.g.:

  • if in DEV environment: https://dev.mycompany.com/myproduct/app
  • if in PROD environment: https://mycompany.com/myproduct/app

Any hints?

like image 649
Sabina Orazem Avatar asked Oct 31 '25 00:10

Sabina Orazem


1 Answers

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.

like image 80
madhead - StandWithUkraine Avatar answered Nov 01 '25 14:11

madhead - StandWithUkraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!