Video in progress
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=100asAPP_LIMITS_UZCARD, the key arrives asuzcard(it becomes lowercase), but keys with dots or dashes can't be provided correctly through an env var. For complex structures,SPRING_APPLICATION_JSONor a config file (mounting the ConfigMap as a file) is more convenient. - Relaxed binding with
@Valueis limited.@Value("${app.allowed-origins}")is found from an env var only if written in kebab-case;@ConfigurationPropertiesis much more reliable here. - You check where a value came from with
/actuator/env(on the internal network) or with--debugin the startup log.
Sign up to mark studied questions and save your progress.