Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 87

    Environment Variables

    Twelve-factor rule #3: store config in the environment.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Twelve-factor rule #3: store config in the environment. Spring Boot 3 maps env vars to properties automatically — SPRING_DATASOURCE_URL becomes spring.datasource.url, and SPRING_DATA_REDIS_HOST maps similarly. TechLearningPRO Orders should boot the same artifact in local, staging, and prod with different env only.

    Prefer env (or a secret store injected as env) over baking YAML profiles with credentials into the image. Profiles select behaviour; env supplies hostnames, URLs, and secret references.

    On Kubernetes, map Secret/ConfigMap keys into env. On Docker Compose, pass -e or an env file that is never committed. Java 21 / Boot 3 does not change the mapping rules — it only raises the bar that misconfig should fail fast at startup.

    This lesson makes Orders twelve-factor clean before production security hardening.

    Purpose of this lesson

    Configure Orders via environment variables and secret injection, with Boot 3 relaxed-binding and no secrets in git.

    Understanding the topic

    Same JAR; different environment; Boot relaxed binding does the mapping.

    • Relaxed binding: FOO_BAR → foo.bar; SPRING_* overrides YAML.
    • Profiles: SPRING_PROFILES_ACTIVE selects behaviour, not passwords.
    • Secrets: Vault / K8s Secrets / cloud secret managers → env at runtime.
    • Fail fast: required properties missing → refuse to start.
    • Local: export vars or use a gitignored .env loaded by your tooling.

    Step-by-step explanation

    1. List every Orders setting that changes per environment (DB URL, Redis host, issuer URI).
    2. Remove hardcoded hosts/passwords from committed YAML; reference ${...} placeholders.
    3. Set env in local shell / Compose; map K8s Secret keys for staging/prod.
    4. Boot Orders and confirm Actuator env (locked down) or logs show the expected profile — never print secret values.

    Informative example

    Env-driven Orders config (placeholders only — no real secrets).

    bash
    # application.yml
    spring:
    datasource:
    url: ${SPRING_DATASOURCE_URL}
    username: ${SPRING_DATASOURCE_USERNAME}
    password: ${SPRING_DATASOURCE_PASSWORD}
    data:
    redis:
    host: ${REDIS_HOST:localhost}
    # Local shell (gitignored values)
    export SPRING_PROFILES_ACTIVE=dev
    export SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/orders
    export SPRING_DATASOURCE_USERNAME=orders_app
    export SPRING_DATASOURCE_PASSWORD=${LOCAL_DB_PASSWORD}
    export REDIS_HOST=localhost
    ./mvnw spring-boot:run
    # Docker
    docker run --rm \
    -e SPRING_PROFILES_ACTIVE=prod \
    -e SPRING_DATASOURCE_URL=${SPRING_DATASOURCE_URL} \
    -e SPRING_DATASOURCE_PASSWORD=${SPRING_DATASOURCE_PASSWORD} \
    techlearningpro/orders:3.2
    # Kubernetes — Secret → env
    env:
    - name: SPRING_DATASOURCE_PASSWORD
    valueFrom:
    secretKeyRef:
    name: orders-db
    key: password

    Real-world use

    A TechLearningPRO staging image once embedded a shared DB password in application-prod.yml. A laptop clone of the repo was enough to reach staging Postgres. Moving credentials to K8s Secrets injected as env — and failing boot when unset — closed the leak and made prod promotion the same artifact.

    Security implications

    Env vars are convenient — and visible to anyone with process or cluster access.

    • Prefer short-lived secret injection over long-lived plaintext in ConfigMaps.
    • Restrict who can kubectl exec or read Secret objects for Orders.
    • Never paste production passwords into chat, tickets, or lesson samples.

    Best practices

    • Document required env vars in README; validate with @ConfigurationProperties + required fields.
    • Use different Secret objects per environment and rotate via the platform.
    • Keep sample configs as placeholders only (${SPRING_DATASOURCE_PASSWORD}).

    Common mistakes

    • Committing .env or YAML with real passwords.
    • Relying on profile-specific YAML for secrets instead of env/secret stores.
    • Logging full env dumps that include credentials during debug.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionHow does Spring Boot map SPRING_DATASOURCE_URL?+

    Answer

    Relaxed binding maps it to spring.datasource.url, overriding file-based config for that property.
    2IntermediateQuestionWhy inject secrets as env instead of baking them into the image?+

    Answer

    One immutable artifact; rotate credentials without rebuilding; reduce secret sprawl in registries and git.
    3IntermediateQuestionWhat is the risk of ConfigMaps for passwords?+

    Answer

    ConfigMaps are not encrypted at rest by default and are often wider-readable than Secrets — use a secret store.

    Hands-on exercise

    Lab. Strip DB credentials from committed YAML. Boot Orders only when SPRING_DATASOURCE_* are set; confirm a missing password fails startup. Wire a K8s (or Compose) secret reference for the password key.

    Summary

    Environment variables keep Orders portable and secret-free in git. Next: harden the production security checklist around that config.

    Ready to mark this lesson complete?Track your journey across the entire course.