pass environment value defined in Kubernetes yaml config to java spring profile

4/19/2019

I have the following in my Dockerfile to run my Springboot app:

ENTRYPOINT [ "java", "-jar", "/code/myapp/target/myapp.jar", "--spring.profiles.active=$ENV_PROFILE"]

I defined my environment variable (ENV_PROFILE) in my k8 YAML config as:

 spec:
  containers:
    - name: myspringboot
      image: myrepo/myapp:latest
      imagePullPolicy: Always
      resources:
        requests:
          cpu: 100m
          memory: 100Mi
      env:
      - name: ENV_PROFILE
        value: "test"

However, the environment name is not getting injected into the java springboot app. It shows as "$ENV_PROFILE" in the log. I also tried with application.properties by adding spring.profiles.active=$ENV_PROFILE and that does not work either.

-- Sonam
kubernetes
spring
spring-boot

2 Answers

4/19/2019

This is because you are not using shell in your ENTRYPOINT. Only shell can make environment variable substitutions. In your case you can use the following ENTRYPOINT:

ENTRYPOINT exec java -jar /code/myapp/target/myapp.jar --spring.profiles.active=$ENV_PROFILE

This syntax involves calling "/bin/sh -c ENTRYPOINT" and "exec" makes sure that java will become PID 1 inside container.

-- Vasily Angapov
Source: StackOverflow

4/19/2019

You can also override the Spring properties (and other properties defined in the application properties) by default, without specifying what environment variable to pass in your properties file. Environment variables have higher precedence then the properties file values.

See also Spring Externalized Configuration.

For example:

 spec:
  containers:
    - name: myspringboot
      image: myrepo/myapp:latest
      imagePullPolicy: Always
      resources:
        requests:
          cpu: 100m
          memory: 100Mi
      env:
      - name: SPRING_PROFILES_ACTIVE
        value: "test"
-- Blokje5
Source: StackOverflow