Environment files and secrets
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's compose.yaml goes into Git, but the database password and the JWT secret must never be committed. Keep the secrets on your own computer and let Compose fill them in when the stack starts.
.env substitution vs env_file
.env is a file next to compose.yaml with NAME=value lines. Compose uses it to replace ${NAME} in compose.yaml before it starts anything, and Git never sees it.
Real passwords must not sit in compose.yaml. Write ${NAME} there instead, and keep the value in a .env file. Compose fills it in before it starts anything.
Example 1 · compose.yaml with .env substitution and an env_file
Runs in: the shoplite-api project folder with Docker 27+
# .env (next to compose.yaml, NOT committed)# MYSQL_ROOT_PASSWORD=r00t-Local-7731# MYSQL_PASSWORD=shop-Local-4410# JWT_SECRET=3q2+7w8kX0yQh1VdM9aLr5uTzP4cN6bE2fJ8gK0sW1o=name: shopliteservices: db: image: mysql:8.4 environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_DATABASE: shoplite MYSQL_USER: shoplite MYSQL_PASSWORD: ${MYSQL_PASSWORD} api: build: . env_file: - api.env # LOG_LEVEL, TZ ... go straight into the container environment: DB_URL: jdbc:mysql://db:3306/shoplite DB_USER: shoplite DB_PASSWORD: ${MYSQL_PASSWORD} # same value as the db user, filled in from .env$ docker compose config
name: shoplite
services:
api:
build:
context: /home/asha/shoplite-api
dockerfile: Dockerfile
environment:
DB_PASSWORD: shop-Local-4410
DB_URL: jdbc:mysql://db:3306/shoplite
DB_USER: shoplite
LOG_LEVEL: INFO
TZ: Asia/Kolkata
db:
environment:
MYSQL_DATABASE: shoplite
MYSQL_PASSWORD: shop-Local-4410
MYSQL_ROOT_PASSWORD: r00t-Local-7731
MYSQL_USER: shoplite
image: mysql:8.4
...What this code does
- The password appears only in
.env;compose.yamlrefers to it twice, so the database user and the API can never get out of sync. LOG_LEVELandTZcome fromapi.envthroughenv_file:and land directly in the API's environment; you cannot use them as${LOG_LEVEL}elsewhere in the file.
This is variable substitution: the values come from your shell's environment and from .env in the same folder. If both define the same name, the shell wins.
env_file: is a different thing. It is a service key that reads a file of KEY=value lines and puts every line straight into that container's environment; those values are not used for ${...} in the compose file. Use .env plus ${...} when you want to see in compose.yaml which values a service gets, and env_file: for a long list you do not want to repeat.
Predict the output
Which password does db get?
compose.yaml has MYSQL_PASSWORD: ${MYSQL_PASSWORD} for the db service.
Round 1 of 2
Only the .env file defines the name. What does db receive?
Required variables: ${JWT_SECRET:?message}
${VAR:?msg} marks a variable as required: if it is missing or empty, Compose stops before starting any container and prints your message.
ShopLite's JWT_SECRET has no safe default, so Compose should refuse to start without it. The snippet shows three forms of ${...}; the Java model after it shows how Compose picks a value.
environment: DB_URL: ${DB_URL:-jdbc:mysql://db:3306/shoplite} # default if missing DB_PASSWORD: ${MYSQL_PASSWORD:?MYSQL_PASSWORD is required} JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required}Example 2 · How Compose fills in ${...}: a small model
import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;
public class SubstitutionDemo { // ${NAME}, ${NAME:-default} or ${NAME:?message} static final Pattern VAR = Pattern.compile("\\$\\{(\\w+)(?::([-?])([^}]*))?}");
static String resolve(String line, Map<String, String> env) { Matcher m = VAR.matcher(line); StringBuilder out = new StringBuilder(); while (m.find()) { String value = env.getOrDefault(m.group(1), ""); if (value.isEmpty() && "-".equals(m.group(2))) { value = m.group(3); } else if (value.isEmpty() && "?".equals(m.group(2))) { throw new IllegalStateException("required variable " + m.group(1) + " is missing a value: " + m.group(3)); } m.appendReplacement(out, Matcher.quoteReplacement(value)); } m.appendTail(out); return out.toString(); }
public static void main(String[] args) { Map<String, String> dotEnv = Map.of("MYSQL_PASSWORD", "shop-Local-4410"); String[] lines = { "DB_PASSWORD: ${MYSQL_PASSWORD}", "DB_URL: ${DB_URL:-jdbc:mysql://db:3306/shoplite}", "JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required}" }; for (String line : lines) { try { System.out.println(resolve(line, dotEnv)); } catch (IllegalStateException e) { System.out.println("error: " + e.getMessage()); } } }}DB_PASSWORD: shop-Local-4410 DB_URL: jdbc:mysql://db:3306/shoplite error: required variable JWT_SECRET is missing a value: JWT_SECRET is required
What this code does
${MYSQL_PASSWORD}is found in the.envvalues;${DB_URL:-...}is missing, so the default after:-is used.${JWT_SECRET:?...}is missing, so resolution stops with the message, the same waydocker compose uprefuses to start. This is a simplified model of Compose's rules, not its real code.
The other forms are ${NAME:-default} (use the default when missing or empty) and plain ${NAME} (missing becomes an empty string, with a warning). An empty DB_PASSWORD or JWT_SECRET is worse than a clear error, because the app may start and fail much later in a confusing way.
Fix the error
Choose the right ${...} form
Compose only warns about the missing value. Pick the replacement for the highlighted line.
Round 1 of 2
Compose must stop when JWT_SECRET is not set.
Error
WARN The "JWT_SECRET" variable is not set. Defaulting to a blank string.
docker compose config: see the resolved file
docker compose config reads compose.yaml, applies .env, defaults and override files, and prints the final file that Compose would really use. Nothing is started.
A value looks wrong and you cannot tell why. One command shows exactly what Compose will use, before anything starts.
Example 3 · docker compose config shows the problem before start-up
Runs in: the shoplite-api project folder with Docker 27+
docker compose config --quiet # .env without JWT_SECRETecho "JWT_SECRET=3q2+7w8kX0yQh1VdM9aLr5uTzP4cN6bE2fJ8gK0sW1o=" >> .envdocker compose config --quiet && echo "compose file OK"docker compose config | grep JWT_SECRET$ docker compose config --quiet
error while interpolating services.api.environment.JWT_SECRET: required variable JWT_SECRET is missing a value: JWT_SECRET is required
$ docker compose config --quiet && echo "compose file OK"
compose file OK
$ docker compose config | grep JWT_SECRET
JWT_SECRET: 3q2+7w8kX0yQh1VdM9aLr5uTzP4cN6bE2fJ8gK0sW1o=What this code does
- The first run fails with your own message and names the exact place in the file, without starting any container.
- After adding the value,
--quietprints nothing and exits with 0, so the&&part runs. The last command shows the resolved value; never paste that output into a chat or an issue.
Run it whenever a value looks wrong: you see at once whether ${MYSQL_PASSWORD} became your password, an empty string or an error. docker compose config --quiet only checks the file and prints nothing when it is valid.
Be careful where you paste the output, because it contains the resolved secrets.
Compose secrets and Spring Boot configtree
A Compose secret is a file that Compose mounts read-only inside the container at /run/secrets/<name>, instead of putting the value in an environment variable.
Environment variables can leak into logs and into docker inspect. A Compose secret hands the container a file instead, and Spring Boot can read a whole folder of them.
# src/main/resources/application.ymlspring: config: import: optional:configtree:/run/secrets/ # optional: works without secrets too datasource: password: ${db_password:${DB_PASSWORD}} # secret file first, then env variableExample 4 · Compose secrets: files in /run/secrets
Runs in: the shoplite-api project folder with Docker 27+
services: db: image: mysql:8.4 environment: MYSQL_DATABASE: shoplite MYSQL_USER: shoplite MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password MYSQL_PASSWORD_FILE: /run/secrets/db_password secrets: - db_root_password - db_password api: build: . environment: DB_URL: jdbc:mysql://db:3306/shoplite DB_USER: shoplite secrets: - db_password # becomes /run/secrets/db_password -> property db_password - jwt_secretsecrets: db_root_password: file: ./secrets/db_root_password.txt db_password: file: ./secrets/db_password.txt jwt_secret: file: ./secrets/jwt_secret.txt$ docker compose exec api ls /run/secrets db_password jwt_secret $ docker compose exec api env | grep -i password (no output: the password is not an environment variable)
What this code does
- Each service lists only the secrets it needs: the API never sees the root password. Top-level
secrets:says which local file holds each one; thesecrets/folder is in.gitignore. - With
optional:configtree:/run/secrets/inapplication.yml, the files become the propertiesdb_passwordandjwt_secret. In ShopLite, pointshoplite.jwt.secretat${jwt_secret:${JWT_SECRET}}the same way as the password.
Example 5 · What configtree does, in plain Java
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Stream;
public class ConfigTreeDemo { static Map<String, String> loadConfigTree(Path dir) throws IOException { Map<String, String> props = new TreeMap<>(); try (Stream<Path> files = Files.list(dir)) { for (Path file : files.toList()) { String value = Files.readString(file); if (value.endsWith("\n")) { value = value.substring(0, value.length() - 1); // drop trailing newline } props.put(file.getFileName().toString(), value); } } return props; }
static String masked(String secret) { return "*".repeat(8) + " (" + secret.length() + " chars)"; }
public static void main(String[] args) throws IOException { Path secrets = Files.createTempDirectory("run-secrets"); // stands in for /run/secrets Files.writeString(secrets.resolve("db_password"), "shop-Local-4410\n"); Files.writeString(secrets.resolve("jwt_secret"), "3q2+7w8kX0yQh1VdM9aLr5uTzP4cN6bE2fJ8gK0sW1o=\n");
Map<String, String> props = loadConfigTree(secrets); props.forEach((name, value) -> System.out.println(name + " = " + masked(value))); System.out.println("password matches: " + props.get("db_password").equals("shop-Local-4410"));
for (Path file : List.of(secrets.resolve("db_password"), secrets.resolve("jwt_secret"), secrets)) { Files.delete(file); } }}db_password = ******** (15 chars) jwt_secret = ******** (44 chars) password matches: true
What this code does
- Each file name becomes a property name and the file text its value, without the trailing newline that editors and
echoadd. Without that step the password would beshop-Local-4410plus a newline and MySQL would reject it. - The program prints only a mask and the length, never the secret. Do the same in your own start-up logs.
Unlike an environment variable, a secret does not show up in docker inspect output or in the environment that child processes inherit.
The MySQL image reads such files through *_FILE variables, for example MYSQL_PASSWORD_FILE: /run/secrets/db_password. Spring Boot reads a whole folder of them with spring.config.import: optional:configtree:/run/secrets/: each file becomes a property named after the file, with the file's text as the value (a trailing newline is dropped). So the file db_password becomes the property db_password.
Order of execution
Move a password into a secret
Put the steps in the order you would do them.
Commit .env.example, never .env
.env.example is a committed copy of .env with every variable name and a safe placeholder value. A new teammate copies it to .env and fills in real values.
A new teammate must know which variables exist, but must never receive your real values. Commit a template and ignore the real file.
# .gitignore.envsecrets/# .env.example (committed: names and placeholders only)MYSQL_ROOT_PASSWORD=change-meMYSQL_PASSWORD=change-meJWT_SECRET=paste-a-random-32-byte-base64-valueYour real .env and any secrets/ folder go into .gitignore, as in the Git section's lesson on ignoring files.
If a real password was ever committed, deleting the file in a new commit is not enough: it is still in the history. Change (rotate) that password, then clean up.
Find the bug
Spot the leaked secret
Both files are about to be committed. Tap the line that leaks a secret.
This is .env.example, the committed template.
Round 1 of 2Next step
Check your understanding
12 quick questions