Estimated time: 45 minutes.
Package a small API as a Docker image with a Dockerfile, run the container with port mapping, then combine web (nginx) + app (Node) + database (PostgreSQL) into a single stack with Docker Compose.
Requirements: use a named volume so the database data survives recreation; have the services call each other by service name on the Compose network (service discovery); publish a port so the stack is reachable from the host.
Acceptance: curl to the web service returns a result containing db_time from the database; the data in the database is intact after the containers are removed and recreated.
Use a Linux host (for example Ubuntu 24.04). Confirm Docker works with the hello-world test image.
docker version
docker run --rm hello-world
Note: If you get permission denied when talking to the Docker daemon, add your user to the docker group (sudo usermod -aG docker $USER) and log in again, or run with sudo.
The project directory contains server.js (a plain Node API using the pg library, which reads credentials from the PG* environment variables on its own) and package.json.
The app returns db_time if it can connect to the database, and otherwise returns db: unreachable — it does not crash.
All files in this exercise live in ~/docker-lab/demo.
The directory name demo is the Compose project name in step 6, which is why the sample output shows demo-web-1 and db.demo_default — if you use a different name, these names change accordingly.
mkdir -p ~/docker-lab/demo && cd ~/docker-lab/demo
cat > server.js <<'EOF'
// server.js — minimal API: returns the time from Postgres if it can connect.
// The pg library reads PGHOST / PGUSER / PGPASSWORD / PGDATABASE from the environment on its own.
const http = require('http');
const { Client } = require('pg');
http.createServer(async (_req, res) => {
const host = process.env.PGHOST || 'localhost';
const client = new Client({ connectionTimeoutMillis: 1500 });
res.setHeader('Content-Type', 'application/json');
try {
await client.connect();
const r = await client.query('SELECT NOW() AS now');
await client.end();
res.end(JSON.stringify({ status: 'ok', db_host: host, db_time: r.rows[0].now }));
} catch (e) {
res.end(JSON.stringify({ status: 'app-up', db_host: host, db: 'unreachable' }));
}
}).listen(3000, () => console.log('app listening on :3000'));
EOF
cat > package.json <<'EOF'
{
"name": "docker-demo-app",
"version": "1.0.0",
"main": "server.js",
"dependencies": { "pg": "^8.13.0" }
}
EOF
ls
In the Dockerfile, put COPY package*.json and the dependency install BEFORE COPY . . so that editing the source does not force a dependency reinstall (this preserves the cache).
Build with an explicit tag (do not rely on latest).
cd ~/docker-lab/demo
cat > Dockerfile <<'EOF'
FROM node:20-alpine
WORKDIR /app
# Copy the manifest and install dependencies BEFORE copying the source → keeps the cache when only code changes
COPY package*.json ./
RUN npm install --omit=dev
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
EOF
docker build -t demo-app:1.0 .
docker images demo-app
Note: For apps that need compilation (TypeScript, frontend), split the build stage from the runtime stage with a multi-stage build so the final image does not contain the toolchain.
Run the container in the background and publish port 3000. There is no database at this point, so the app returns db: unreachable (still a 200) — which shows the app is alive on its own.
EXPOSE in the Dockerfile is only documentation; the port is reachable thanks to -p.
docker run -d --name app -p 3000:3000 demo-app:1.0
docker ps
docker logs app
curl -s localhost:3000
Note: EXPOSE does not publish a port by itself (Dockerfile ref §EXPOSE); you must pass -p HOST:CONTAINER when running.
Run Postgres with a named volume attached, create a table and write data, remove the container, start a new container attached to the same volume, then read the data back.
The data must still be there because a volume lives independently of the container lifecycle.
docker volume create pgdata
docker run -d --name db -e POSTGRES_PASSWORD=changeme -v pgdata:/var/lib/postgresql/data postgres:16-alpine
sleep 8 # wait for Postgres to start
docker exec db psql -U postgres -c "CREATE TABLE t(x int); INSERT INTO t VALUES (42);"
docker rm -f db
docker run -d --name db -e POSTGRES_PASSWORD=changeme -v pgdata:/var/lib/postgresql/data postgres:16-alpine
sleep 8
docker exec db psql -U postgres -c "SELECT * FROM t;"
Note: The writable layer is deleted on docker rm; only a volume or bind mount keeps the data (Docker: volumes).
Clean up before step 6: docker rm -f app db.
Write nginx.conf (a reverse proxy to app:3000) and compose.yaml (web + app + db + a named volume). Compose creates a dedicated network for the project, so services call each other by name.
You reach the stack from the host through the web service's port 8080; web proxies to app; app queries db by the name db.
cd ~/docker-lab/demo
cat > nginx.conf <<'EOF'
server {
listen 80;
location / {
proxy_pass http://app:3000; # "app" is resolved by name on the Compose network
}
}
EOF
cat > compose.yaml <<'EOF'
services:
web:
image: nginx:alpine
ports:
- "8080:80"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- app
app:
build: .
environment:
PGHOST: db # reach the database by the service NAME
PGUSER: app
PGPASSWORD: changeme
PGDATABASE: appdb
depends_on:
- db
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: changeme # change this value for real use
POSTGRES_DB: appdb
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:
EOF
# bring it up and check (run in ~/docker-lab/demo → project named "demo")
docker compose up -d --build
docker compose ps
docker compose exec app nslookup db
curl -s localhost:8080
Note: depends_on only guarantees start order; it does not wait for the database to be ready —
add a healthcheck plus depends_on:condition:service_healthy when needed (Compose file:services).
Clean up with: docker compose down -v.
On later builds, the dependency-install layer is served from cache as long as only the source changed.
docker build -t demo-app:1.0 .
docker images demo-app
Result:
=> [1/5] FROM node:20-alpine
=> [2/5] WORKDIR /app
=> [3/5] COPY package*.json ./
=> [4/5] RUN npm install --omit=dev
=> [5/5] COPY . .
Successfully tagged demo-app:1.0
REPOSITORY TAG IMAGE ID SIZE
demo-app 1.0 a1b2c3d4e5f6 142MB
Note: Edit server.js and rebuild: the steps up to npm install show CACHED, and only COPY . . runs again.
The app stays up even though the database cannot be reached.
docker run -d --name app -p 3000:3000 demo-app:1.0
docker ps
curl -s localhost:3000
Result:
CONTAINER ID IMAGE PORTS NAMES
f3a9c1d2e4b5 demo-app:1.0 0.0.0.0:3000->3000/tcp app
{"status":"app-up","db_host":"localhost","db":"unreachable"}
Note: A PORTS column showing 0.0.0.0:3000->3000/tcp means the port was published thanks to -p.
Write the value 42, remove the container, run it again, and reading still returns 42.
docker exec db psql -U postgres -c "INSERT INTO t VALUES (42);"
docker rm -f db
docker run -d --name db -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=changeme postgres:16-alpine
docker exec db psql -U postgres -c "SELECT * FROM t;"
Result:
x
----
42
(1 row)
Note: The container was removed and recreated, yet the data is still there — because it lives in the pgdata volume, not in the writable layer.
From inside the app container, the name db resolves to an internal IP.
docker compose exec app nslookup db
Result:
Name: db
Address 1: 172.19.0.2 db.demo_default
Note: On the default bridge, calling by name fails (IP only); a Compose or custom bridge network has internal DNS (Docker: bridge network).
End-to-end flow: the host calls web (8080) → web proxies to app → app queries db → returns db_time.
docker compose ps
curl -s localhost:8080
Result:
NAME IMAGE STATUS PORTS
demo-web-1 nginx:alpine Up 0.0.0.0:8080->80/tcp
demo-app-1 demo-app Up
demo-db-1 postgres:16-alpine Up
{"status":"ok","db_host":"db","db_time":"2026-07-18T09:12:44.512Z"}
Note: A result containing db_time proves the web → app → db chain works through service discovery + the volume.