spring-bootkubernetes

Spring Boot: override application.yml properties from Kubernetes ConfigMap


I need to oveeride some of properties defined in a application.yml of Spring Boot application running in k8s. How can I do this? The only way I found is to mount whole application.yml but I only need to override one property.


Solution

  • Spring Boot Apps should override properties in the configuration files (aka, in their application.yml most of the times) with environment variables.

    Assuming the App is deployed on Kubernetes with a Pod (but it doesn't matter, Deployments, StatefulSets, Jobs are all the same regarding environment) you can inject environment variables inside the container by either directly assigning them to the Deployment itself, or with a ConfigMap (or a Secret, should the property be more secure and masked)

    apiVersion: v1
    kind: Pod
    metadata:
      name: example
    spec:
      containers:
      - name: example-container
        image: example-image:latest
        env:
        - name: THIS_IS_AN_ENV_VARIABLE
          value: "Hello from the environment"
        - name: spring.persistence.url
          value: "The persistence url, for example"
    

    Even better, you can inject all the content of a ConfigMap as environment variables:

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: example-config
    data:
      spring.persistence.url: "your persistence url"
      spring.mail.user: "your mail user"
    

    And then your Pod:

    apiVersion: v1
    kind: Pod
    metadata:
      name: example
    spec:
      containers:
      - name: example-container
        image: example-image:latest
        envFrom:
        - configMapRef:
            name: example-config
    

    Inside the container, the variables will be in the environment.. and Spring should use them to override variables with same name which are defined (or maybe not even defined) in your application.yml

    For more info:

    https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/ https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/ https://docs.spring.io/spring-boot/docs/1.3.3.RELEASE/reference/html/boot-features-external-config.html