Skip to lesson

Environment variables in containers

The same ShopLite image must talk to the database on your laptop today and to the real one on the server tomorrow. Rebuilding the image for every place would be slow and risky.

-e KEY=value and --env-file app.env

An environment variable is a named text value, such as APP_ENV=prod, that a process receives when it starts. Containers use them for configuration, so the same image runs anywhere.

ShopLite's AppConfigDemo reads three variables and falls back to defaults. Run it with -e, then with a file, and only the output changes.

Example 1 · The AppConfig program from module 1

AppConfigDemo.javaJava
import java.util.Map;
record AppConfig(String env, String dbUrl, int port) {
    static AppConfig from(Map<String, String> vars) {        String env = vars.getOrDefault("APP_ENV", "dev");        String dbUrl = vars.get("DB_URL");        if (dbUrl == null || dbUrl.isBlank()) {            if (env.equals("prod")) {                throw new IllegalStateException("DB_URL is required when APP_ENV=prod");            }            dbUrl = "jdbc:mysql://localhost:3306/shoplite";        }        int port = Integer.parseInt(vars.getOrDefault("PORT", "8080"));        return new AppConfig(env, dbUrl, port);    }}
public class AppConfigDemo {    public static void main(String[] args) {        AppConfig config = AppConfig.from(System.getenv());        System.out.println("APP_ENV = " + config.env());        System.out.println("DB_URL  = " + config.dbUrl());        System.out.println("PORT    = " + config.port());    }}
Output
APP_ENV = dev
DB_URL  = jdbc:mysql://localhost:3306/shoplite
PORT    = 8080

What this code does

  • System.getenv() returns all environment variables as a Map<String, String>; AppConfig.from reads three of them and falls back to dev defaults.
  • Run with no variables set, it prints the defaults. In prod a missing DB_URL is an error, because a wrong database is worse than no start at all.

Example 2 · Passing variables with -e and --env-file

Runs in: a terminal with Docker installed, in the folder that holds AppConfigDemo.java

Terminal
docker run --rm -e PORT=9000 -v "$PWD":/app -w /app eclipse-temurin:25-jdk sh -c "javac AppConfigDemo.java && java AppConfigDemo"cat app.envdocker run --rm --env-file app.env -v "$PWD":/app -w /app eclipse-temurin:25-jdk sh -c "javac AppConfigDemo.java && java AppConfigDemo"
Sample output
APP_ENV = dev
DB_URL  = jdbc:mysql://localhost:3306/shoplite
PORT    = 9000
# app.env - test settings, not committed
APP_ENV=test
DB_URL=jdbc:mysql://shoplite-db:3306/shoplite
PORT=8081
APP_ENV = test
DB_URL  = jdbc:mysql://shoplite-db:3306/shoplite
PORT    = 8081

What this code does

  • -e PORT=9000 changed one value; the other two kept their defaults from the Java code.
  • --env-file app.env passed three values at once. The # line is a comment and is not passed to the container.
  • The same file and the same program gave a different configuration; the code and the image did not change.

Example 3 · Three runs of the same program, simulated in Java

AppConfigRunsDemo.javaJava
import java.util.Map;
record AppConfig(String env, String dbUrl, int port) {
    static AppConfig from(Map<String, String> vars) {        String env = vars.getOrDefault("APP_ENV", "dev");        String dbUrl = vars.get("DB_URL");        if (dbUrl == null || dbUrl.isBlank()) {            if (env.equals("prod")) {                throw new IllegalStateException("DB_URL is required when APP_ENV=prod");            }            dbUrl = "jdbc:mysql://localhost:3306/shoplite";        }        int port = Integer.parseInt(vars.getOrDefault("PORT", "8080"));        return new AppConfig(env, dbUrl, port);    }}
public class AppConfigRunsDemo {    static void run(String command, Map<String, String> vars) {        System.out.println("$ " + command);        try {            AppConfig config = AppConfig.from(vars);            System.out.println("APP_ENV = " + config.env());            System.out.println("DB_URL  = " + config.dbUrl());            System.out.println("PORT    = " + config.port());        } catch (IllegalStateException e) {            System.out.println("Startup failed: " + e.getMessage());        }    }
    public static void main(String[] args) {        run("docker run ... -e PORT=9000", Map.of("PORT", "9000"));        System.out.println();        run("docker run ... --env-file prod.env", Map.of(                "APP_ENV", "prod",                "DB_URL", "jdbc:mysql://shoplite-db:3306/shoplite"));        System.out.println();        run("docker run ... -e APP_ENV=prod", Map.of("APP_ENV", "prod"));    }}
Output
$ docker run ... -e PORT=9000
APP_ENV = dev
DB_URL  = jdbc:mysql://localhost:3306/shoplite
PORT    = 9000

$ docker run ... --env-file prod.env
APP_ENV = prod
DB_URL  = jdbc:mysql://shoplite-db:3306/shoplite
PORT    = 8080

$ docker run ... -e APP_ENV=prod
Startup failed: DB_URL is required when APP_ENV=prod

What this code does

  • AppConfig.from takes any Map, so a Map.of(...) can stand in for the variables each docker run would pass. This is also how you test config code without a container.
  • The third run is prod without DB_URL: the program stops with a clear message instead of quietly using the laptop database. In a container the uncaught exception ends the process with exit code 1.

-e KEY=value sets one variable for the container's main process. --env-file app.env reads many from a file, one KEY=value per line. Java reads them with System.getenv("KEY"), or System.getenv() for all of them as a Map.

Rules for an env file:

  • One KEY=value per line; lines starting with # are comments; blank lines are skipped.
  • No quotes: docker run --env-file keeps them, so DB_PASSWORD="abc" gives the value "abc" with the quote marks.
  • No spaces around = and no export in front.
  • A line with only a name, such as JWT_SECRET, copies that variable from your own terminal if it is set there.

Find the bug

Spot the bad env-file line

docker run --env-file reads these files. Click the line that gives a wrong value or fails.

The app prints the password with quote marks around it.

Round 1 of 3

Image defaults with ENV, and which value wins

ENV in a Dockerfile bakes a default environment variable into the image, for example ENV APP_ENV=dev PORT=8080. Every container from that image starts with it unless docker run replaces it.

A Dockerfile can bake in a default value. A run command can replace it. The Java example after the Dockerfile shows who wins.

Terminal
# part of a Dockerfile (the Dockerising Spring Boot module writes full ones)FROM eclipse-temurin:25-jreENV APP_ENV=dev PORT=8080# at run time the -e value replaces the image default# (shoplite-config:0.1 = an image that runs AppConfigDemo)docker run --rm -e APP_ENV=prod -e DB_URL=jdbc:mysql://shoplite-db:3306/shoplite shoplite-config:0.1

Example 4 · Which value wins: code default, ENV, --env-file or -e

EnvPrecedenceDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class EnvPrecedenceDemo {    public static void main(String[] args) {        Map<String, String> codeDefaults = Map.of("APP_ENV", "dev", "PORT", "8080", "LOG_LEVEL", "INFO");        Map<String, String> imageEnv = Map.of("APP_ENV", "dev", "PORT", "8080");        Map<String, String> envFile = Map.of("APP_ENV", "test", "LOG_LEVEL", "DEBUG");        Map<String, String> dashE = Map.of("APP_ENV", "prod");
        // lowest priority first; a later layer overwrites an earlier one        Map<String, String> finalEnv = new LinkedHashMap<>();        Map<String, String> source = new LinkedHashMap<>();        List<String> layerNames = List.of("code default", "image ENV", "--env-file", "-e flag");        List<Map<String, String>> layers = List.of(codeDefaults, imageEnv, envFile, dashE);        for (int i = 0; i < layers.size(); i++) {            for (Map.Entry<String, String> e : layers.get(i).entrySet()) {                finalEnv.put(e.getKey(), e.getValue());                source.put(e.getKey(), layerNames.get(i));            }        }
        for (String key : List.of("APP_ENV", "PORT", "LOG_LEVEL")) {            System.out.println(key + " = " + finalEnv.get(key) + "   (from " + source.get(key) + ")");        }    }}
Output
APP_ENV = prod   (from -e flag)
PORT = 8080   (from image ENV)
LOG_LEVEL = DEBUG   (from --env-file)

What this code does

  • The layers are applied from lowest to highest priority, and each put replaces the value from a lower layer. APP_ENV is set four times; -e comes last and wins.
  • PORT is set only by the code default and the image, so the image's value stays. LOG_LEVEL comes from the env file because no higher layer mentions it.

From lowest to highest priority: the default written in your Java code, then the image's ENV, then --env-file, then -e. A later layer replaces a value from an earlier one; values it does not mention stay as they were.

Order of execution

Lowest to highest priority

Put the sources in order, from the weakest to the one that always wins.

Put only safe, non-secret defaults in ENV: anyone who pulls the image can read them with docker image inspect.

docker inspect and docker exec env: what the container received

The effective environment is the full list of variables a container really received, after the image ENV, the env file and -e values are combined. Check it before you blame the app.

Start a container with two variables, then ask Docker what it received in two different ways.

Example 5 · Checking a running container with inspect and exec

Runs in: a terminal with Docker installed, in the folder that holds HealthServer.java

Terminal
docker run -d --name hello -p 9000:9000 -e PORT=9000 -e APP_ENV=test -v "$PWD":/app -w /app eclipse-temurin:25-jdk java HealthServer.javadocker inspect --format '{{json .Config.Env}}' hellodocker exec hello envdocker exec hello printenv PORT
Sample output
3e8b0d5a7c1f...
["PATH=/opt/java/openjdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","JAVA_HOME=/opt/java/openjdk","LANG=en_US.UTF-8","LANGUAGE=en_US:en","LC_ALL=en_US.UTF-8","JAVA_VERSION=jdk-25.0.1+8","PORT=9000","APP_ENV=test"]
PATH=/opt/java/openjdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=3e8b0d5a7c1f
JAVA_HOME=/opt/java/openjdk
LANG=en_US.UTF-8
LANGUAGE=en_US:en
LC_ALL=en_US.UTF-8
JAVA_VERSION=jdk-25.0.1+8
PORT=9000
APP_ENV=test
HOME=/root
9000

What this code does

  • PORT=9000 reached the container, so HealthServer listens on 9000 inside; the -p 9000:9000 mapping matches it. Your Java version and the order of the list may differ.
  • docker exec hello env shows the same variables plus a few Docker adds itself, such as HOSTNAME (the short container ID) and HOME.
  • If a variable you passed is missing here, the app cannot see it either: check for a typo in the name or a missing --env-file.

docker inspect prints a container's full configuration as JSON; --format '{{json .Config.Env}}' picks just the variables. It works on stopped containers too. docker exec NAME env runs the env command inside a running container and prints what its processes see.

Both lists include the image's own variables such as PATH and JAVA_HOME, next to yours.

Spring Boot relaxed binding: SPRING_DATASOURCE_URL

Relaxed binding is Spring Boot's rule that lets an environment variable set any property: dots become underscores, dashes are removed and the name is written in capitals, so spring.datasource.url becomes SPRING_DATASOURCE_URL.

ShopLite's application.yml reads its settings from placeholders. Below the yaml, a Java program turns property names into variable names.

YAML
spring:  datasource:    url: ${DB_URL:jdbc:mysql://localhost:3306/shoplite}   # dev default only    username: ${DB_USER}    password: ${DB_PASSWORD}shoplite:  jwt-secret: ${JWT_SECRET}                              # no default on purpose

Example 6 · Property name to environment variable name

RelaxedBindingDemo.javaJava
import java.util.List;import java.util.Locale;
public class RelaxedBindingDemo {    // Spring Boot's rule for env var names: dots -> underscores, drop dashes,    // [index] -> _index_, then upper case    static String toEnvName(String property) {        return property                .replace("[", "_")                .replace("]", "")                .replace(".", "_")                .replace("-", "")                .toUpperCase(Locale.ROOT);    }
    public static void main(String[] args) {        List<String> properties = List.of(                "spring.datasource.url",                "spring.datasource.username",                "spring.profiles.active",                "server.port",                "shoplite.jwt-secret",                "shoplite.cors.allowed-origins[0]");        for (String p : properties) {            System.out.printf("%-33s <- %s%n", p, toEnvName(p));        }    }}
Output
spring.datasource.url             <- SPRING_DATASOURCE_URL
spring.datasource.username        <- SPRING_DATASOURCE_USERNAME
spring.profiles.active            <- SPRING_PROFILES_ACTIVE
server.port                       <- SERVER_PORT
shoplite.jwt-secret               <- SHOPLITE_JWTSECRET
shoplite.cors.allowed-origins[0]  <- SHOPLITE_CORS_ALLOWEDORIGINS_0

What this code does

  • Each property on the left can be set by the variable on the right. Dots become underscores, dashes disappear (jwt-secret becomes JWTSECRET) and everything is upper case.
  • SPRING_PROFILES_ACTIVE=prod is the variable ShopLite uses to pick its prod profile in a container.

server.port becomes SERVER_PORT, and a list index [0] becomes _0.

Environment variables rank above application.yml, so SPRING_DATASOURCE_URL replaces the URL from the file without editing it. ShopLite's application.yml also reads ${DB_URL:...} placeholders, so you can set either DB_URL or SPRING_DATASOURCE_URL; if both are set, SPRING_DATASOURCE_URL wins.

Secrets in -e: shell history and docker inspect

A secret is a value that must stay private, such as a database password or the JWT signing key. It must never be committed to Git, baked into an image or typed into a shared command line.

Never type a real password on a command line. Compare the risky way with two safer ones.

Terminal
# risky: the password is in shell history and in docker inspectdocker run -d --name shoplite-api -e DB_PASSWORD=s3cret-pass shoplite-api:1.2.0history | grep DB_PASSWORD# better: real values live in .env, which Git ignoresecho ".env" >> .gitignoredocker run -d --name shoplite-api --env-file .env shoplite-api:1.2.0# also fine: name only, the value comes from your terminal's variabledocker run -d --name shoplite-api -e DB_PASSWORD shoplite-api:1.2.0

Typed with -e DB_PASSWORD=..., a secret is saved in your shell history and shows up in docker inspect for anyone who can run Docker commands on that machine.

Keep secrets in a .env file that is listed in .gitignore, and commit only .env.example with placeholder values. --env-file .env keeps the value out of your history and out of Git. It still appears in docker inspect, which is why servers later use a secret store; the Docker Compose and cloud deployment modules show those.

If a secret was ever committed to Git, deleting the file is not enough: it stays in the history. Change (rotate) the password or key.

Next step

Check your understanding

11 quick questions