Sobes.tech
Senior

How to configure environment variables in Spring Boot via Kubernetes (ConfigMap/Secrets)?

sobes.tech AI

Answer from AI

In Kubernetes, ConfigMap and Secrets are commonly used to pass configuration data and secrets to a Spring Boot application, mounted as environment variables.

To configure environment variables via ConfigMap/Secrets, you need to:

  1. Create a ConfigMap or Secret with the required keys and values.

Example ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/mydb
  SPRING_DATASOURCE_USERNAME: user
  1. In the Deployment manifest, add these data as environment variables in the container:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: spring-app
spec:
  template:
    spec:
      containers:
      - name: app
        image: my-spring-app:latest
        envFrom:
        - configMapRef:
            name: app-config
        - secretRef:
            name: app-secrets
  1. In the Spring Boot application, environment variables are automatically picked up thanks to naming conventions (for example, SPRING_DATASOURCE_URL corresponds to the property spring.datasource.url).

Thus, you can centrally manage configuration and secrets outside the application image, which is convenient for different environments and secure for sensitive data.

How to configure environment variables in Spring Boot… - sobes.tech