Video in progress

Strong Middle 🌱 Spring

In Kubernetes, how do you provide spring.datasource.url or a list-style setting through an environment variable?

Spring Boot does relaxed binding: dots become _, dashes are removed, everything is uppercase: SPRING_DATASOURCE_URL. A list element is given with an index: APP_ALLOWEDORIGINS_0_. Be careful with map keys, because an env var turns the key uppercase.

📖 Answer

The rule: take the property name, replace . with _, remove -, and convert to uppercase.

Property Env var
spring.datasource.url SPRING_DATASOURCE_URL
server.shutdown-timeout SERVER_SHUTDOWNTIMEOUT
app.allowed-origins[0] APP_ALLOWEDORIGINS_0_
app.allowed-origins[1] APP_ALLOWEDORIGINS_1_

For a list there's also a simpler way: one value separated by commas: APP_ALLOWEDORIGINS=https://a.uz,https://b.uz. This binds correctly to a List<String>.

# Kubernetes deployment
env:
  - name: SPRING_PROFILES_ACTIVE
    value: prod
  - name: SPRING_DATASOURCE_URL
    value: jdbc:postgresql://db:5432/shop
  - name: SPRING_DATASOURCE_PASSWORD
    valueFrom:
      secretKeyRef: { name: shop-db, key: password }

Subtle points:

  • Map keys. If you provide app.limits.uzcard=100 as APP_LIMITS_UZCARD, the key arrives as uzcard (it becomes lowercase), but keys with dots or dashes can't be provided correctly through an env var. For complex structures, SPRING_APPLICATION_JSON or a config file (mounting the ConfigMap as a file) is more convenient.
  • Relaxed binding with @Value is limited. @Value("${app.allowed-origins}") is found from an env var only if written in kebab-case; @ConfigurationProperties is much more reliable here.
  • You check where a value came from with /actuator/env (on the internal network) or with --debug in the startup log.