Skip to lesson

ShopLite's API runs in a container, yet your browser cannot open it. A container has its own private network, so you must open a door on purpose.

A health server in Java with com.sun.net.httpserver

A port is a numbered door on a computer that a server listens on. A request names the computer and the port it wants; web apps such as ShopLite use 8080.

A tiny Java web server gives us something to reach. First the server that runs until you stop it, then the same server as a self-test you can run anywhere.

Example 1 · HealthServer: a server that runs until stopped

Runs in: a terminal (stop it with Ctrl+C)

HealthServer.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.nio.charset.StandardCharsets;
public class HealthServer {    public static void main(String[] args) throws IOException {        int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));        HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0);        server.createContext("/health", exchange -> {            byte[] body = "{\"status\":\"UP\"}".getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().set("Content-Type", "application/json");            exchange.sendResponseHeaders(200, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        System.out.println("HealthServer listening on 0.0.0.0:" + port);    }}
Sample output
HealthServer listening on 0.0.0.0:8080

What this code does

  • HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0) listens on every network interface; createContext("/health", ...) answers that one path with a JSON body and status 200.
  • server.start() starts background threads, so main ends but the program keeps running. Run it with java HealthServer.java and open http://localhost:8080/health; stop it with Ctrl+C.

Example 2 · The same server as a self-test

HealthCheckDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
public class HealthCheckDemo {    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/health", exchange -> {            byte[] body = "{\"status\":\"UP\"}".getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().set("Content-Type", "application/json");            exchange.sendResponseHeaders(200, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        int port = server.getAddress().getPort();
        HttpClient client = HttpClient.newHttpClient();        HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/health")).build();        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());        System.out.println("GET /health -> " + response.statusCode() + " " + response.body());
        server.stop(0);        System.out.println("Server stopped");    }}
Output
GET /health -> 200 {"status":"UP"}
Server stopped

What this code does

  • Port 0 asks the operating system for any free port, and server.getAddress().getPort() tells us which one we got, so the demo never clashes with another program.
  • HttpClient (Java 11+) sends a real HTTP request to the server, prints the status and body, then server.stop(0) ends it so the program finishes.

HttpServer (package com.sun.net.httpserver, part of the JDK) is a small built-in web server. A health endpoint is a URL that answers {"status":"UP"} when the app is alive.

HealthServer reads its port from the PORT environment variable (default 8080) and keeps running until it is stopped. The self-test starts, calls itself once and stops, so you can run it anywhere.

Spring Boot apps get the same kind of endpoint from Actuator at /actuator/health; this tiny server lets us learn port mapping without a full project.

Why localhost:8080 fails: the container network is isolated

A container network is the private network every container gets, with its own IP address and its own localhost. A server on port 8080 inside the container does not listen on your computer's port 8080.

Start the server in a container without publishing anything, then try to reach it from your own computer.

Example 3 · Without -p: the server runs but localhost fails

Runs in: a terminal with Docker installed

Terminal
docker run -d --name hello -v "$PWD":/app -w /app eclipse-temurin:25-jdk java HealthServer.javadocker logs hellocurl http://localhost:8080/healthdocker ps --filter name=hello
Sample output
8d4a1f7c2b9e...
HealthServer listening on 0.0.0.0:8080
curl: (7) Failed to connect to localhost port 8080 after 0 ms: Couldn't connect to server
CONTAINER ID   IMAGE                    COMMAND                  CREATED          STATUS          PORTS     NAMES
8d4a1f7c2b9e   eclipse-temurin:25-jdk   "/__cacert_entrypoin…"   15 seconds ago   Up 14 seconds             hello

What this code does

  • The logs prove the server is up inside the container, listening on the container's port 8080.
  • curl on your computer gets "connection refused" (error 7) because nothing listens on your computer's port 8080. The empty PORTS column confirms no port is published.

So curl http://localhost:8080/health on your computer finds nothing and fails with connection refused, even though docker logs hello says the server is listening. The PORTS column of docker ps is empty: no door has been opened from your computer into the container.

Predict the output

Can curl reach it?

The container runs HealthServer on port 8080. Pick what curl prints.

Round 1 of 2

Started with no -p at all.

docker run -d --name hello shoplite-health
curl http://localhost:8080/health
In Windows PowerShell, curl can be a different command. Type curl.exe to use the real curl that ships with Windows 10 and 11.

-p host:container, and EXPOSE is documentation only

Port mapping, written -p HOST:CONTAINER, forwards a port on your computer to a port inside the container. With -p 9090:8080 you open localhost:9090 and reach the app that listens on 8080 inside.

Publish a port with -p. These runs start the same app twice, on host ports 8080 and 9090, and a small Java program reads -p specs.

Port mapping. curl calls localhost:9090 on your computer. Docker forwards it through -p 9090:8080 to port 8080 inside the container, where HealthServer listens on 0.0.0.0. Without -p the call is refused. Left of the colon is your computer, right is the container.

Example 4 · -p 8080:8080 and -p 9090:8080

Runs in: a terminal with Docker installed

Terminal
docker rm -f hellodocker run -d --name hello -p 8080:8080 -v "$PWD":/app -w /app eclipse-temurin:25-jdk java HealthServer.javacurl http://localhost:8080/healthdocker run -d --name hello-9090 -p 9090:8080 -v "$PWD":/app -w /app eclipse-temurin:25-jdk java HealthServer.javacurl http://localhost:9090/healthdocker port hello-9090docker ps --format "table {{.Names}}\t{{.Ports}}"
Sample output
hello
2c7e9a1b4d6f...
{"status":"UP"}
5f1b3d8e0a2c...
{"status":"UP"}
8080/tcp -> 0.0.0.0:9090
8080/tcp -> [::]:9090
NAMES        PORTS
hello-9090   0.0.0.0:9090->8080/tcp, [::]:9090->8080/tcp
hello        0.0.0.0:8080->8080/tcp, [::]:8080->8080/tcp

What this code does

  • Both containers listen on 8080 inside; they do not clash because each has its own network. Only the host ports (8080 and 9090) must differ.
  • Read 0.0.0.0:9090->8080/tcp as "host port 9090 on every host address goes to container port 8080". [::] is the same mapping for IPv6.
  • docker port hello-9090 lists the mappings of one container; --format picks only the columns you want from docker ps.

Example 5 · Reading -p mappings in Java

PortSpecDemo.javaJava
public class PortSpecDemo {    static String describe(String spec) {        String[] parts = spec.split(":");        if (parts.length == 1) {            return "container " + parts[0] + " <- a random free host port";        }        if (parts.length == 2) {            return "container " + parts[1] + " <- host port " + parts[0] + " on every host address";        }        return "container " + parts[2] + " <- host port " + parts[1] + " on " + parts[0] + " only";    }
    public static void main(String[] args) {        String[] specs = {"8080:8080", "9090:8080", "127.0.0.1:9090:8080", "8080"};        for (String spec : specs) {            System.out.println("-p " + spec + " => " + describe(spec));        }    }}
Output
-p 8080:8080 => container 8080 <- host port 8080 on every host address
-p 9090:8080 => container 8080 <- host port 9090 on every host address
-p 127.0.0.1:9090:8080 => container 8080 <- host port 9090 on 127.0.0.1 only
-p 8080 => container 8080 <- a random free host port

What this code does

  • The last part is always the container port. With two parts the first is the host port; with three the first is a host address, so 127.0.0.1:9090:8080 is reachable only from your own computer, not from other devices on the office Wi-Fi.
  • -p 8080 alone publishes container port 8080 on a random free host port; docker port tells you which one.

The left side is always your computer, the right side is the container. You can run three copies of the same image with -p 8081:8080, -p 8082:8080 and -p 8083:8080: one container port, three different host ports.

EXPOSE 8080 in a Dockerfile only documents which port the app uses. It publishes nothing. Only -p (or -P, which publishes every exposed port to a random host port) opens a door.

Fix the error

Swap the two sides

The app listens on 8080 inside. You want http://localhost:9090. Fix line 1.

The -p numbers are the wrong way round.

docker run -d --name hello -p 8080:9090 shoplite-health
curl http://localhost:9090/health

Error

curl: (7) Failed to connect to localhost port 9090 after 0 ms: Couldn't connect to server

Binding inside the container: 0.0.0.0 vs 127.0.0.1

A bind address is the network address a server listens on. 127.0.0.1 (loopback) accepts only connections from the same machine; 0.0.0.0 means every network interface.

Run two small servers and let Java tell us which addresses they listen on.

Example 6 · 127.0.0.1 vs 0.0.0.0 in a Java server

BindAddressDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetAddress;import java.net.InetSocketAddress;
public class BindAddressDemo {    static void show(String host) throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress(host, 0), 0);        server.start();        InetAddress bound = server.getAddress().getAddress();        System.out.println("Bound to " + host);        System.out.println("  loopback only (127.x.x.x)? " + bound.isLoopbackAddress());        System.out.println("  every network interface?   " + bound.isAnyLocalAddress());        server.stop(0);    }
    public static void main(String[] args) throws IOException {        show("127.0.0.1");        show("0.0.0.0");    }}
Output
Bound to 127.0.0.1
  loopback only (127.x.x.x)? true
  every network interface?   false
Bound to 0.0.0.0
  loopback only (127.x.x.x)? false
  every network interface?   true

What this code does

  • isLoopbackAddress() is true for 127.0.0.1: that server accepts only connections that start on the same machine, which inside a container means the container itself.
  • isAnyLocalAddress() is true for 0.0.0.0, the "every interface" address. This is the one that receives traffic Docker forwards through -p.

Docker's forwarded traffic arrives on the container's own network interface, not on its loopback. So a server bound to 127.0.0.1 inside a container is unreachable even with a correct -p: curl usually reports (52) Empty reply from server or (56) Connection reset by peer. Bind to 0.0.0.0 in containers.

In practice:

  • new InetSocketAddress("0.0.0.0", port): reachable through -p.
  • new InetSocketAddress("127.0.0.1", port) or "localhost": reachable only from inside the container.
  • Spring Boot binds to every interface by default. If someone set server.address=127.0.0.1, remove it for containers.

Find the bug

Find the loopback bind

Both servers are unreachable through -p 8080:8080. Click the guilty line.

A Java server that listens only inside the container.

Round 1 of 2

"port is already allocated": finding who uses the port

A host port conflict happens when you publish a host port that another container or program already holds. Docker reports it as port is already allocated (or not available on Docker Desktop).

A host port belongs to one program at a time. When a second run asks for 8080, Docker refuses; the commands below find the owner.

Terminal
$ docker run -d --name hello2 -p 8080:8080 -v "$PWD":/app -w /app eclipse-temurin:25-jdk java HealthServer.javadocker: Error response from daemon: driver failed programming external connectivity on endpoint hello2 (3a9f0c...): Bind for 0.0.0.0:8080 failed: port is already allocated.docker ps --filter publish=8080     # is it another container?netstat -ano | findstr :8080        # Windows: last column is the PIDtasklist /FI "PID eq 12345"         # Windows: which program has that PIDlsof -i :8080                       # macOS / Linux: program and PID

If another container publishes host port 8080, a new -p 8080:8080 fails with port is already allocated. If a program outside Docker (a local Spring Boot run, a local MySQL) holds the port, Docker Desktop reports that the port is not available.

Fix it by choosing a free host port (-p 8081:8080) or by stopping whatever holds the port. First find out who that is.

A failed docker run can still leave a container in the Created state with that name. Remove it with docker rm hello2 before you try again.

Next step

Check your understanding

11 quick questions