Skip to lesson

Deploying a container image

The ShopLite image passed CI, but it is still just a file in a registry. To let users reach it you must start it somewhere and tell the platform four things. Get one wrong and the deploy restarts forever.

Deploying the image to a container platform

A health check path is the URL the platform calls to decide whether the app can serve traffic. It must answer 200 only when the app is really ready, such as /actuator/health.

A container platform needs four settings: the exact image tag CI pushed, the port, the environment variables and a health check path. Here are ShopLite's:

Text
Image            ghcr.io/asha-rao/shoplite-api:3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0Registry login   asha-rao / a read-only token (packages: read)Port             PORT=8080 (or the platform's value; the app reads it)Health check     /actuator/healthInstance size    512 MB memoryEnv vars         SPRING_PROFILES_ACTIVE, DB_URL, DB_USER, DB_PASSWORD,                 FLYWAY_USER, FLYWAY_PASSWORD, JWT_SECRET, CORS_ALLOWED_ORIGINS,                 JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=75

Example 1 · server.port=${PORT:8080} on three platforms

PortResolutionDemo.javaJava
import java.util.Map;
public class PortResolutionDemo {    // What Spring does for server.port: ${PORT:8080}    static int serverPort(Map<String, String> env) {        return Integer.parseInt(env.getOrDefault("PORT", "8080"));    }
    static void show(String where, Map<String, String> env, int platformSendsTo) {        int port = serverPort(env);        String result = port == platformSendsTo ? "traffic arrives" : "no answer, restart loop";        System.out.printf("%-22s app listens on %5d, platform sends to %5d -> %s%n",                where, port, platformSendsTo, result);    }
    public static void main(String[] args) {        show("Laptop (no PORT)", Map.of(), 8080);        show("Platform with PORT", Map.of("PORT", "10000"), 10000);        show("VM with Compose", Map.of(), 8080);        // The bug: a fixed server.port=8080 ignores PORT        int fixed = 8080;        System.out.println("Fixed port 8080 on the platform: "                + (fixed == 10000 ? "works" : "health check fails on 10000"));    }}
Output
Laptop (no PORT)       app listens on  8080, platform sends to  8080 -> traffic arrives
Platform with PORT     app listens on 10000, platform sends to 10000 -> traffic arrives
VM with Compose        app listens on  8080, platform sends to  8080 -> traffic arrives
Fixed port 8080 on the platform: health check fails on 10000

What this code does

  • serverPort mirrors the placeholder ${PORT:8080}: the environment wins, and 8080 is the default when nothing is set.
  • One image works in every place because the port is configuration, not code. A fixed port works only where the platform happens to use the same number.

Many platforms choose the port for you and pass it in a PORT environment variable, then send traffic only to that port. ShopLite handles both cases with one line in application.yml: server.port: ${PORT:8080}, meaning "use PORT if the platform set it, otherwise 8080".

If the package is private, also add a registry login with a read-only token. The health check path can be /actuator/health, or /actuator/health/readiness from the next module.

Deploying to a VM with Docker Compose

compose.yaml is the file that describes the containers running on a VM: the API image, its settings, a memory limit, a health check and Caddy in front. docker compose up -d starts or updates them.

On a VM, one compose.yaml describes the whole running app: the API, its settings and Caddy, a small web server in front. Here is ShopLite's file and one deploy:

Example 2 · deploy/compose.yaml on the VM

Runs in: a Linux VM with Docker, in /opt/shoplite (copied from deploy/ in the repository)

YAML
# /opt/shoplite/compose.yaml   (.env next to it holds IMAGE_TAG=<sha>)name: shopliteservices:  api:    image: ghcr.io/asha-rao/shoplite-api:${IMAGE_TAG:?set IMAGE_TAG in .env}    env_file: shoplite.env            # DB_*, FLYWAY_*, JWT_SECRET, CORS_ALLOWED_ORIGINS    environment:      SPRING_PROFILES_ACTIVE: prod      JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError    expose:      - "8080"                        # reachable by caddy only, not published    mem_limit: 512m    restart: unless-stopped    healthcheck:      test: ["CMD-SHELL", "wget -qO- http://localhost:8080/actuator/health/readiness || exit 1"]      interval: 15s      timeout: 3s      retries: 3      start_period: 60s  caddy:    image: caddy:2.10    ports:      - "80:80"      - "443:443"    volumes:      - ./Caddyfile:/etc/caddy/Caddyfile:ro      - caddy-data:/data      - caddy-config:/config    depends_on:      api:        condition: service_healthy    restart: unless-stoppedvolumes:  caddy-data:  caddy-config:# Deploy a new build:#   echo "IMAGE_TAG=3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0" > .env#   docker compose pull api && docker compose up -d
Sample output
$ docker compose pull api && docker compose up -d
[+] Pulling 1/1
 ✔ api Pulled                                                     7.2s
[+] Running 2/2
 ✔ Container shoplite-api-1    Healthy                           41.3s
 ✔ Container shoplite-caddy-1  Running                            0.0s

What this code does

  • ${IMAGE_TAG:?...} stops Compose with that message if the tag is missing, so the VM never silently runs an old or latest image. expose keeps port 8080 private; only Caddy publishes ports 80 and 443.
  • mem_limit: 512m gives the container the same limit a 512 MB platform plan would, and JAVA_TOOL_OPTIONS sizes the heap inside it. The health check uses BusyBox wget, which the Alpine-based JRE image from the Dockerising module includes; wget exits with an error on a 503, so a not-ready app counts as unhealthy.

Secrets sit next to it in shoplite.env (readable only by the deploy user), and a .env file holds one line, IMAGE_TAG=<sha>, which Compose puts into the image name.

A deploy is two commands: docker compose pull downloads the new image, and docker compose up -d recreates only the containers whose image or settings changed. The API restarts briefly; the managed database is not touched.

Order of execution

Deploy on the VM, step by step

Put one deploy of ShopLite on the VM in order.

Reading the first deploy logs

Exit code 137 means the process was killed with SIGKILL, usually because the container used more memory than its limit. Platforms may call it OOMKilled or exceeded memory limit.

The first deploy rarely works, and the log tells you why. The most common failure is the wrong port:

Example 3 · First deploy log: the wrong port

Runs in: the container platform's deploy log for the shoplite-api service

Terminal
# application.yml had a fixed port:   server.port: 8080# The platform sets PORT=10000 and checks /actuator/health on that port.# Fix:                                server.port: ${PORT:8080}
Sample output
==> Pulling image ghcr.io/asha-rao/shoplite-api:3f9c2e1b7d4a...
==> Starting service
Picked up JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError
INFO  c.shoplite.ShopliteApiApplication : The following 1 profile is active: "prod"
INFO  o.s.boot.tomcat.TomcatWebServer   : Tomcat started on port 8080 (http) with context path '/'
INFO  c.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 9.41 seconds
==> Health check failed: no response on port 10000 at /actuator/health
==> Health check failed: no response on port 10000 at /actuator/health
==> Deploy failed: the service did not respond on its port. Rolling back to the previous version.

What this code does

  • The app itself is fine: Spring Boot started in 9 seconds. The mismatch is visible in two lines: Tomcat on 8080, the platform checking 10000. Wording differs between platforms, but the pattern is the same.
  • Many platforms keep the previous version running when a new one fails its health check, which is why the health check path matters: without it, a broken release would receive traffic.

Example 4 · Proving the port mismatch with a real server

PortMismatchDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.Map;
public class PortMismatchDemo {    static int freePort() throws IOException {        try (ServerSocket s = new ServerSocket(0)) {            return s.getLocalPort();        }    }
    static HttpServer startApp(int port) throws IOException {        // 127.0.0.1 for this demo; inside a container the app listens on 0.0.0.0        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);        server.createContext("/actuator/health", exchange -> {            byte[] body = "{\"status\":\"UP\"}".getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().add("Content-Type", "application/json");            exchange.sendResponseHeaders(200, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        return server;    }
    static String probe(HttpClient client, int port) {        HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/actuator/health"))                .timeout(Duration.ofSeconds(5)).build();        try {            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());            return response.statusCode() + " " + response.body();        } catch (IOException e) {            return "no answer";        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            return "interrupted";        }    }
    public static void main(String[] args) throws IOException {        int platformPort = freePort();              // what the platform puts in PORT        int fixedPort = freePort();                 // stands for a hard-coded server.port        while (fixedPort == platformPort) {            fixedPort = freePort();        }        Map<String, String> env = Map.of("PORT", String.valueOf(platformPort));        HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
        HttpServer wrong = startApp(fixedPort);        System.out.println("App ignores PORT    -> platform probe: " + probe(client, platformPort));        wrong.stop(0);
        HttpServer right = startApp(Integer.parseInt(env.getOrDefault("PORT", "8080")));        System.out.println("App reads PORT      -> platform probe: " + probe(client, platformPort));        right.stop(0);    }}
Output
App ignores PORT    -> platform probe: no answer
App reads PORT      -> platform probe: 200 {"status":"UP"}

What this code does

  • Two free ports stand for the platform's PORT and a hard-coded port. The "platform" (an HttpClient) always probes PORT, exactly as a real health check does.
  • The first app is healthy but listens elsewhere, so the probe gets no answer. The second reads PORT from the environment map and the same probe gets 200 {"status":"UP"}.

In that log Spring Boot starts fine, but the platform probes PORT (say 10000), gets no answer and restarts the container again and again. Fix it with server.port: ${PORT:8080}, or set the platform's port to 8080. Inside a container the app must listen on all interfaces (0.0.0.0), which Spring Boot does by default.

Out-of-memory restarts are the second common failure: the container is killed with exit code 137, often a minute after start or under the first real load, because the JVM asked for more than the 512 MB limit. The next section sizes it.

Fix the error

Read the log, fix the line

Each log points at one line. Pick the replacement.

Round 1 of 2

Spring started, but the platform sees no answer.

server:
port: 8080

Error

Tomcat started on port 8080
Health check failed: no response on port 10000

Sizing memory: the JVM in 512 MB

MaxRAMPercentage is a JVM option, -XX:MaxRAMPercentage=75, that sets the maximum heap as a share of the container's memory limit. The default is 25%, which leaves a 512 MB container a 128 MB heap.

A Java process needs more than its heap: class data, compiled code, thread stacks and the garbage collector take memory too. The program below splits a 512 MB container:

Example 5 · Heap and non-heap in a 512 MB container

HeapBudgetDemo.javaJava
public class HeapBudgetDemo {    public static void main(String[] args) {        int containerMb = 512;        int nonHeapMb = 110;     // rough estimate for a small Spring Boot API        int minHeapMb = 192;     // below this, ShopLite runs out of heap under load
        for (int percent : new int[] {25, 50, 75, 90}) {            int heap = containerMb * percent / 100;            int left = containerMb - heap;            String verdict;            if (heap < minHeapMb) {                verdict = "OutOfMemoryError: Java heap space under load";            } else if (left < nonHeapMb) {                verdict = "container killed, exit code 137";            } else {                verdict = "fits";            }            System.out.printf("MaxRAMPercentage=%-2d heap %3d MB, other %3d MB -> %s%n",                    percent, heap, left, verdict);        }    }}
Output
MaxRAMPercentage=25 heap 128 MB, other 384 MB -> OutOfMemoryError: Java heap space under load
MaxRAMPercentage=50 heap 256 MB, other 256 MB -> fits
MaxRAMPercentage=75 heap 384 MB, other 128 MB -> fits
MaxRAMPercentage=90 heap 460 MB, other  52 MB -> container killed, exit code 137

What this code does

  • A simplified model with estimated numbers: the heap gets the percentage, and everything else (metaspace, code, threads, GC) must fit in the rest.
  • The default 25% wastes memory and starves the heap; 90% leaves too little for the JVM itself, so the kernel kills the container. 75% is a common choice that uses the plan well.

The heap is where objects live; everything else is non-heap, roughly 100 to 150 MB for a small Spring Boot API. Since Java 10 the JVM reads the container's limit, and with only 25% for the heap you get OutOfMemoryError: Java heap space under load. -XX:MaxRAMPercentage=75 gives about 384 MB of heap and leaves about 128 MB for the rest.

Set it through JAVA_TOOL_OPTIONS, which every JVM reads at start (it prints Picked up JAVA_TOOL_OPTIONS: ...), so the Dockerfile stays unchanged.

Predict the output

How big is the heap?

Work out the maximum heap from the container limit.

Round 1 of 2

What is the maximum heap?

Container limit: 1024 MB
JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=75
These numbers are a starting point, not a rule. Watch the memory graph after the deploy, and give the app 768 MB or 1 GB if it stays near the limit.

Verifying the deploy

A deploy is finished only when you have seen it work from outside. Three curl calls check health, a real API call and the live version:

Terminal
curl -s https://api.shoplite.example/actuator/healthcurl -s https://api.shoplite.example/apicurl -s -o /dev/null -w "%{http_code}\n" "https://api.shoplite.example/api/v1/products?size=1"

Example 6 · Verifying the live deploy from your laptop

Runs in: a terminal on your laptop, after the deploy

Terminal
curl -s https://api.shoplite.example/actuator/healthcurl -s https://api.shoplite.example/apicurl -s "https://api.shoplite.example/api/v1/products?size=1"curl -s -o /dev/null -w "%{http_code}\n" https://api.shoplite.example/api/v1/me
Sample output
{"groups":["liveness","readiness"],"status":"UP"}
{"name":"shoplite-api","version":"1.2.0"}
{"content":[],"page":0,"size":1,"totalElements":0,"totalPages":0}
401

What this code does

  • Health is UP, /api confirms the name and version that are live, and the product list answers 200 with no rows because production has no sample data yet.
  • The last call checks that security works in production too: /api/v1/me without a token must be 401, not 200 and not 500.

ShopLite's GET /api returns the application name and version, a quick way to confirm which build is live. A fresh production database has no products (sample data is dev-only), so an empty product page with status 200 is the correct answer.

Next step

Check your understanding

11 quick questions