Development, test and production environments
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite runs fine on your laptop, but on the test server it crashes, and the code is identical. Something around the code is different. Where do the differences hide, and how do you control them?
The "works on my machine" problem
An environment is one complete place where your program runs: a computer, its operating system, its JDK, its database and its settings.
"Works on my machine" bugs appear when the same code meets a different computer. The program below compares ShopLite's laptop with its server.
Example 1 · Comparing a laptop with a server
import java.util.Map;import java.util.TreeMap;
public class EnvDiffDemo { static void compare(Map<String, String> laptop, Map<String, String> server) { Map<String, String> sortedLaptop = new TreeMap<>(laptop); int differences = 0; for (String key : sortedLaptop.keySet()) { String mine = sortedLaptop.get(key); String theirs = server.getOrDefault(key, "(missing)"); if (!mine.equals(theirs)) { System.out.println(key + ": laptop=" + mine + ", server=" + theirs); differences++; } } System.out.println(differences + " differences found"); }
public static void main(String[] args) { Map<String, String> laptop = Map.of( "JDK", "21", "MySQL", "8.4", "OS", "Windows 11", "upload folder", "C:\\shoplite\\uploads", "DB_PASSWORD", "set"); Map<String, String> server = Map.of( "JDK", "17", "MySQL", "8.0", "OS", "Ubuntu 24.04", "upload folder", "/var/shoplite/uploads"); compare(laptop, server); }}DB_PASSWORD: laptop=set, server=(missing) JDK: laptop=21, server=17 MySQL: laptop=8.4, server=8.0 OS: laptop=Windows 11, server=Ubuntu 24.04 upload folder: laptop=C:\shoplite\uploads, server=/var/shoplite/uploads 5 differences found
What this code does
- Each computer is a
Mapof facts. The program walks the laptop's facts in sorted order (TreeMap) and prints every value the server does not share. - Five differences, and every one of them can break the same jar: an older JDK, an older MySQL, a Windows-only path and a password that exists only on the laptop.
- In a real project nobody writes this list down, which is why "works on my machine" bugs are hard to find.
The differences are small but deadly: a laptop with JDK 21 and a server with JDK 17, or a path like C:\shoplite\uploads that means nothing on Linux. The usual four:
- Different JDK version: code compiled for a newer Java will not start on an older one.
- Different database version: a SQL feature or default behaves differently.
- Different operating system: Windows paths, line endings and file-name case.
- Missing settings: a password or URL that only exists on one computer.
Dev, test and production
Dev / test / prod are the three usual environments: dev is your own laptop, test is a shared place (usually a CI server) with fresh test data, and prod (production) is the real server that real customers use.
Each environment has a different job, so some values must differ. The program below prints the three jobs; the code that runs in them must stay the same.
Example 2 · Three environments, three jobs
import java.util.List;
record Environment(String name, String usedBy, String data, String logLevel) {}
public class EnvironmentsDemo { public static void main(String[] args) { List<Environment> environments = List.of( new Environment("dev", "one developer", "fake sample rows", "DEBUG"), new Environment("test", "the CI server", "fresh test data", "INFO"), new Environment("prod", "real customers", "real orders", "WARN"));
for (Environment e : environments) { System.out.printf("%-5s | %-15s | %-16s | %s%n", e.name(), e.usedBy(), e.data(), e.logLevel()); } }}dev | one developer | fake sample rows | DEBUG test | the CI server | fresh test data | INFO prod | real customers | real orders | WARN
What this code does
- A record
Environmentholds what is different about each place: who uses it, what data it holds and how much it logs. printfwith%-15spads each column to a fixed width so the rows line up as a small table.- Notice what is missing from the record: the code version. It is the same in all three rows.
A CI server is a computer that builds and tests every push automatically. The values that differ between environments:
- Data: sample rows in dev, fresh test data in test, real orders in prod.
- URLs:
localhostin dev, a CI database in test, the real database host in prod. - Secrets: easy passwords in dev, real secrets in prod that no developer types by hand.
- Log level:
DEBUG(very detailed) in dev,INFOorWARN(only important lines) in prod.
One build, only configuration changes
An artifact is the file your build produces and you deploy, such as shoplite-api-1.2.0.jar. Build it once and run the same file in every environment.
Build the jar once and copy that exact file to test and prod; only the configuration, the settings around the code, changes. The example runs one AppConfig in three environments.
Example 3 · The same AppConfig in dev, test and prod
import java.util.List;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 SameArtifactDemo { public static void main(String[] args) { // One build, three environments: only the variables change. Map<String, String> dev = Map.of(); Map<String, String> test = Map.of( "APP_ENV", "test", "DB_URL", "jdbc:mysql://ci-db:3306/shoplite_test"); Map<String, String> prod = Map.of( "APP_ENV", "prod", "DB_URL", "jdbc:mysql://db.shoplite.in:3306/shoplite", "PORT", "80");
for (Map<String, String> vars : List.of(dev, test, prod)) { System.out.println(AppConfig.from(vars)); } }}AppConfig[env=dev, dbUrl=jdbc:mysql://localhost:3306/shoplite, port=8080] AppConfig[env=test, dbUrl=jdbc:mysql://ci-db:3306/shoplite_test, port=8080] AppConfig[env=prod, dbUrl=jdbc:mysql://db.shoplite.in:3306/shoplite, port=80]
What this code does
- One compiled program, three maps of variables. Each map plays the role of one environment.
- Dev sets nothing and gets every default. Test sets
APP_ENVand its own database. Prod sets the real database and port 80. - The record's automatic
toString()prints all three fields, so you can see the effective config in one line.
This is the core idea of the twelve-factor app, a well-known list of rules for apps that run on servers. Its config rule: keep settings that change per environment outside the code, in environment variables (next section).
If you rebuild the jar for each environment, the file that passed the tests is not the file that runs in prod. Building once removes that risk.
Order of execution
Build once, run everywhere
Put the steps in the right order.
Reading configuration from environment variables
An environment variable is a named text value, such as APP_ENV=prod, that the operating system hands to every program it starts.
System.getenv() returns every environment variable as a Map<String, String>. The program reads APP_ENV, DB_URL and PORT, each with a default, inside one small record, AppConfig.
Example 4 · AppConfigDemo: read the real environment
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()); }}APP_ENV = dev DB_URL = jdbc:mysql://localhost:3306/shoplite PORT = 8080
What this code does
AppConfig.from(System.getenv())passes the real environment variables of this run.- With nothing set, every value comes from a default, which is exactly what a developer wants on day one.
- This output assumes you have not set
APP_ENV,DB_URLorPORTin your terminal. Set one and run again to see it change.
A missing variable is simply not in the map, so getOrDefault("PORT", "8080") gives a safe default. Keeping all the reading inside AppConfig means the rest of the app never calls System.getenv itself.
Map instead of calling System.getenv() inside. That lets you test it with Map.of(...) and pretend to be any environment, as the next examples do.Failing fast when a required value is missing
Fail fast means the app checks its configuration at start-up and stops at once, with a clear message, when something required is missing.
A default is fine in dev, but a prod app that quietly uses localhost as its database is a serious bug. So AppConfig.from throws IllegalStateException when APP_ENV is prod and DB_URL is missing.
Example 5 · Fail fast: dev, prod without DB_URL, prod with DB_URL
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 FailFastDemo { static void start(String label, Map<String, String> vars) { System.out.println("Run " + label); try { AppConfig config = AppConfig.from(vars); System.out.println(" Started with " + config.dbUrl()); } catch (IllegalStateException e) { System.out.println(" Startup failed: " + e.getMessage()); } }
public static void main(String[] args) { start("1 (dev, nothing set)", Map.of()); start("2 (prod, DB_URL forgotten)", Map.of("APP_ENV", "prod")); start("3 (prod, DB_URL set)", Map.of( "APP_ENV", "prod", "DB_URL", "jdbc:mysql://db.shoplite.in:3306/shoplite")); }}Run 1 (dev, nothing set) Started with jdbc:mysql://localhost:3306/shoplite Run 2 (prod, DB_URL forgotten) Startup failed: DB_URL is required when APP_ENV=prod Run 3 (prod, DB_URL set) Started with jdbc:mysql://db.shoplite.in:3306/shoplite
What this code does
- The same
AppConfig.fromis called with three maps. Run 2 is prod withDB_URLforgotten, so it throws. startcatchesIllegalStateExceptionand prints the message, so you can see all three runs in one program. A real app would let the exception stop it.- Run 3 shows that the check costs nothing once the variable is set.
Example 6 · Both runs from a real terminal
Runs in: a terminal with JDK 17 or newer, in the folder with AppConfigDemo.java
# Compile once (Git Bash, macOS Terminal or Linux)javac AppConfigDemo.java# Run 1: test settings, given as variables for this one commandAPP_ENV=test PORT=9090 java AppConfigDemo# Run 2: prod, but DB_URL was forgottenAPP_ENV=prod java AppConfigDemoecho "exit code: $?"APP_ENV = test DB_URL = jdbc:mysql://localhost:3306/shoplite PORT = 9090 Exception in thread "main" java.lang.IllegalStateException: DB_URL is required when APP_ENV=prod at AppConfig.from(AppConfigDemo.java:10) at AppConfigDemo.main(AppConfigDemo.java:21) exit code: 1
What this code does
APP_ENV=test PORT=9090 java AppConfigDemosets the two variables only for that one command, so the program sees test settings.- In run 2 the exception is not caught, so Java prints it with its stack trace and the process ends with exit code 1. Scripts and servers treat a non-zero exit code as "start-up failed".
- Compile with
javacfirst and run the class. On Java 21,java AppConfigDemo.java(source-file mode) launches the first class in the file, theAppConfigrecord, which has nomain.
The app dies in the first second, the message names the exact variable, and nobody has to search the logs at night to find out why orders are failing.
Predict the output
Predict the start-up
Choose what AppConfig.from does.
Round 1 of 2
Only APP_ENV=prod is set. What happens?
$env:APP_ENV="prod" on its own line, then run java AppConfigDemo. The NAME=value command form shown here works in Git Bash, macOS Terminal and Linux.Next step
Check your understanding
11 quick questions