App2 · Docker Networking
App2 - Calls App1 Over the Docker Network
Another zero-dependency Node.js service - and the demo of container-to-container networking, one of the core Docker skills. App2 does not call localhost. It calls http://app1:3000, where app1 is the service name from docker-compose.yml.
What it does
| Endpoint | Method | Response |
|---|---|---|
/health | GET | {"status":"healthy","service":"app2"} |
/api/call-app1 | GET | POSTs to App1 and returns App1’s full response |
/ | GET | Info page |
app2/server.js
server.js
const http = require("http");
const APP1_URL = process.env.APP1_URL || "http://app1:3000";
const server = http.createServer(async (req, res) => {
if (req.url === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ status: "healthy", service: "app2" }));
}
if (req.url === "/api/call-app1") {
try {
const response = await fetch(`${APP1_URL}/api/receive`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "hello from app2", source: "app2" }),
});
const data = await response.json();
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(
JSON.stringify({ service: "app2", called: APP1_URL, app1_response: data })
);
} catch (err) {
res.writeHead(500, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ service: "app2", error: String(err) }));
}
}
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("App2 - calls App1 over the Docker network (Docker Workshop)\n");
});
server.listen(3000, () => console.log("App2 listening on :3000"));
app2/Dockerfile
Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY server.js .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
How the name app1 resolves
Docker Compose creates a network and registers every service name as a DNS entry:
- Inside the compose network, containers reach each other by service name + container port.
localhostinside a container means that container - not the host, not other containers.APP1_URLis an environment variable (seedocker-compose.yml), so the target is configurable without touching code.
Run it (with the whole stack)
docker compose up -d
# App2 -> App1, over the Docker network
curl http://localhost:5002/api/call-app1
Expected response:
{
"service": "app2",
"called": "http://app1:3000",
"app1_response": {
"status": "ok",
"service": "app1",
"received": { "message": "hello from app2", "source": "app2" },
"request_count": 1
}
}
Prove it is the DNS doing the work
Next steps
- Full port map and teardown: 🐳 Run with Docker Only
- Front door of the stack: nginx (see Run with Docker Only)