Practice: deploying to the cloud
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Deployment goes wrong in a few predictable ways: the wrong host, a laptop config in production, a log nobody read closely, and a pipeline that deploys before it checks. Try these checks and see what you miss.
Choosing a host: match the need to the model
Start from what the app needs, not from a brand. The program below picks a host for three scenarios, checking the strongest need first:
Example 1 · Picking a host for three scenarios
import java.util.List;
record Need(String app, boolean mustStayAwake, boolean needsPrivateNetwork, int budgetRs) {}
public class HostChoiceDemo { static String choose(Need n) { if (n.needsPrivateNetwork()) { return "big-cloud container service + managed MySQL"; } if (!n.mustStayAwake()) { return "free platform plan (sleeping is fine)"; } if (n.budgetRs() >= 500) { return "small VM with Compose, or a non-sleeping platform plan"; } return "apply for student credits first"; }
public static void main(String[] args) { List<Need> needs = List.of( new Need("College fest page, 2 days", false, false, 0), new Need("ShopLite in my resume", true, false, 800), new Need("Internship team API", true, true, 5000)); for (Need n : needs) { System.out.println(n.app() + " -> " + choose(n)); } }}College fest page, 2 days -> free platform plan (sleeping is fine) ShopLite in my resume -> small VM with Compose, or a non-sleeping platform plan Internship team API -> big-cloud container service + managed MySQL
What this code does
- The checks run from the strongest need down: private networking decides first, then whether the app may sleep, then the budget.
- The answers are reasons, not brands. In an interview, the reason ("it must stay awake on a student budget") matters more than the provider's name.
A two-day college fest page can sleep between visits, so a free plan is fine. A portfolio API on your resume must answer at any hour on a student budget: a small VM or a non-sleeping plan. A team service that needs private networks belongs on a big cloud's container service.
The database is a separate decision: ShopLite needs MySQL 8.4, and if the platform offers only PostgreSQL you add a managed MySQL from another provider in the same region. Review: Hosting options for a student project (opens in a new tab).
Mistake: a production config copied from a laptop
The most common unsafe config is the dev file with a new URL. The program below reviews a copied config and finds four problems:
Example 2 · Finding the four problems in a copied config
import java.util.LinkedHashMap;import java.util.Map;
public class ProdConfigLintDemo { public static void main(String[] args) { Map<String, String> prod = new LinkedHashMap<>(); prod.put("spring.datasource.username", "root"); prod.put("spring.jpa.hibernate.ddl-auto", "update"); prod.put("shoplite.jwt.secret", "${JWT_SECRET:changeme}"); prod.put("logging.level.com.shoplite", "DEBUG"); prod.put("server.port", "${PORT:8080}");
int problems = 0; for (Map.Entry<String, String> e : prod.entrySet()) { String key = e.getKey(); String value = e.getValue(); String issue = null; if (key.endsWith("username") && value.equals("root")) { issue = "use shoplite_app, not root"; } else if (key.endsWith("ddl-auto") && !value.equals("validate")) { issue = "must be validate; Flyway owns the schema"; } else if (key.endsWith("secret") && !value.matches("\\$\\{[A-Z_]+}")) { issue = "secret value or default in the file"; } else if (key.startsWith("logging.level") && value.equals("DEBUG")) { issue = "use INFO in production"; } if (issue != null) { problems++; System.out.println(key + "=" + value + " -> " + issue); } } System.out.println(problems + " problems"); }}spring.datasource.username=root -> use shoplite_app, not root
spring.jpa.hibernate.ddl-auto=update -> must be validate; Flyway owns the schema
shoplite.jwt.secret=${JWT_SECRET:changeme} -> secret value or default in the file
logging.level.com.shoplite=DEBUG -> use INFO in production
4 problemsWhat this code does
- Each rule is one line of review: the secret rule accepts only a bare placeholder such as
${JWT_SECRET}, so${JWT_SECRET:changeme}with its weak default is caught. server.port=${PORT:8080}passes: a default is fine for a port, which is not a secret.
The four problems: the app logs in as root, ddl-auto is update, a secret is written in the YAML (often as a default like ${JWT_SECRET:changeme}), and logging is DEBUG.
The fix is the prod profile: shoplite_app with row rights only, validate, ${JWT_SECRET} with no default, INFO logs, and every per-server value supplied by the platform. Review: Configuration and secrets in production (opens in a new tab).
Find the bug
Spot the unsafe line
Tap the line that a reviewer would reject.
Database login in production.
Round 1 of 3Diagnosing deploy failures from the log
Read the first error, not the last line. The program below matches four log excerpts to their causes and fixes:
Example 3 · Diagnosing four deploy logs
import java.util.LinkedHashMap;import java.util.Map;
public class DeployFailureDemo { static String diagnose(String log) { if (log.contains("no response on port")) { return "app ignores PORT -> server.port: ${PORT:8080}"; } if (log.contains("137") || log.contains("OOMKilled")) { return "out of memory -> -XX:MaxRAMPercentage=75 or more memory"; } if (log.contains("insecure transport")) { return "database requires TLS -> sslMode=REQUIRED in DB_URL"; } if (log.contains("Could not resolve placeholder")) { String name = log.substring(log.indexOf('\'') + 1, log.indexOf('\'', log.indexOf('\'') + 1)); return "missing env var " + name + " -> add it on the platform"; } return "read further up the log"; }
public static void main(String[] args) { Map<String, String> logs = new LinkedHashMap<>(); logs.put("Deploy 1", "Health check failed: no response on port 10000 at /actuator/health"); logs.put("Deploy 2", "Container shoplite-api exited with code 137 (OOMKilled=true)"); logs.put("Deploy 3", "java.sql.SQLException: Connections using insecure transport are prohibited " + "while --require_secure_transport=ON."); logs.put("Deploy 4", "Could not resolve placeholder 'JWT_SECRET' in value \"${JWT_SECRET}\""); logs.forEach((deploy, log) -> System.out.println(deploy + ": " + diagnose(log))); }}Deploy 1: app ignores PORT -> server.port: ${PORT:8080}
Deploy 2: out of memory -> -XX:MaxRAMPercentage=75 or more memory
Deploy 3: database requires TLS -> sslMode=REQUIRED in DB_URL
Deploy 4: missing env var JWT_SECRET -> add it on the platformWhat this code does
- Each failure has a short, unique phrase in its log line; matching on it is exactly what you do by eye when you scan a deploy log.
- For the missing variable, the code reads the name between the first pair of single quotes, so the fix names the exact setting to add.
Four excerpts cover most first deploys:
no response on port 10000afterTomcat started on port 8080→ the app ignoresPORT. Fix:server.port: ${PORT:8080}.exit code 137,OOMKilledor "exceeded memory limit" → the JVM is too big for the container. Fix:-XX:MaxRAMPercentage=75or more memory.Connections using insecure transport are prohibited while --require_secure_transport=ON→ the database insists on TLS. Fix:sslMode=REQUIREDinDB_URL.Could not resolve placeholder 'JWT_SECRET'→ a required variable is missing on the platform. Fix: add it and redeploy.
Predict the output
What does this log mean?
Read the log lines and pick the cause.
Round 1 of 4
What is wrong?
The order of a safe automatic deploy
A safe pipeline moves forward only when the step before it is green. The program below stops at the first red step:
Example 4 · A pipeline that stops at the first red step
import java.util.LinkedHashMap;import java.util.Map;
public class SafeDeployOrderDemo { static void run(String title, Map<String, Boolean> steps) { System.out.println(title); for (Map.Entry<String, Boolean> step : steps.entrySet()) { if (!step.getValue()) { System.out.println(" x " + step.getKey() + " -> stop, production unchanged"); return; } System.out.println(" ok " + step.getKey()); } System.out.println(" release is live"); }
static Map<String, Boolean> pipeline(boolean tests, boolean smoke) { Map<String, Boolean> steps = new LinkedHashMap<>(); steps.put("build and test (./mvnw -B verify)", tests); steps.put("push image :<sha>", true); steps.put("approval", true); steps.put("deploy :<sha>", true); steps.put("smoke test", smoke); return steps; }
public static void main(String[] args) { run("Push 1:", pipeline(true, true)); run("Push 2:", pipeline(false, true)); run("Push 3:", pipeline(true, false)); }}Push 1: ok build and test (./mvnw -B verify) ok push image :<sha> ok approval ok deploy :<sha> ok smoke test release is live Push 2: x build and test (./mvnw -B verify) -> stop, production unchanged Push 3: ok build and test (./mvnw -B verify) ok push image :<sha> ok approval ok deploy :<sha> x smoke test -> stop, production unchanged
What this code does
- A
LinkedHashMapkeeps the steps in pipeline order, and the loop stops at the first false value, just likeneeds:between jobs. - Push 3 shows the limit of this simple model: the deploy already happened when the smoke test failed. The run turns red so you act, usually by redeploying the previous SHA (the Running in Production module covers rollback).
The order: build and test (./mvnw -B verify), push the image tagged with the commit SHA, wait for approval if the environment has reviewers, deploy that exact tag, then smoke test the live URL with retries. Each step trusts the one before: deploying before the tests ships untested code, and skipping the smoke test means users find the broken release. Review: Automatic deploys from the main branch (opens in a new tab).
Explaining your deployment in an interview
Interviewers ask "how did you deploy it?" to see if you understand what you built. A good answer takes about a minute and follows the request: where it runs (VM with Compose and Caddy, or a platform, plus managed MySQL), how a change gets there (PR runs tests; main builds a SHA image and deploys it after tests, with a smoke test), and how secrets are safe (platform env vars and GitHub environment secrets, nothing in Git or the image, least-privilege DB user, TLS to the database).
End with one trade-off you chose on purpose, such as "a single VM is a single point of failure, which is acceptable for a portfolio project; for real users I would run two instances behind a load balancer".
Finish up
Mark complete & continue
Next: Project: ShopLite goes online