57.16 Project 16: 3-tier app: React frontend, Node.js API and PostgreSQL
Friends, today we build a college fest events app like a small BookMyShow: React frontend, Node API, PostgreSQL. nginx serves the built React files and proxies /api to Node. Type every command yourself.
मित्रांनो, आज आपण छोट्या BookMyShow सारखी college fest events app build करू: React frontend, Node API, PostgreSQL. nginx build झालेली React files देते आणि /api Node कडे पाठवते. प्रत्येक command स्वतः टाइप करा.
दोस्तों, आज हम छोटी BookMyShow जैसी college fest events app build करेंगे: React frontend, Node API, PostgreSQL. nginx build हुई React files देता है और /api Node को भेजता है. हर command खुद टाइप कीजिए.
What you will learn in this lesson
- Why front, API and database are three tiers.
- How a multi-stage build puts React into nginx.
- How nginx proxies /api to the Node service.
- How Postgres holds seats with an atomic UPDATE.
- How a dev Compose file adds hot reload.
1. Start from a real problem
Suppose we build the events app for a college fest in Pune, like a small BookMyShow: students see events and register for them.
Putting React, Node and Postgres on one laptop by hand causes version fights. With Docker each tier is a container on its own network path.
BookMyShow and district fest portals use the same three-tier idea even when the scale is larger.
2. API and database
Step 1: Folders and API code
Why: Express + pg pool.
What: api/server.js lists events and registers with an atomic seats_left update.
Example 1: Make folders
Type this:
mkdir -p three-tier/api three-tier/web/src three-tier/db three-tier/web-nginx && cd three-tier && pwd
You will see:
/home/you/three-tier
What it means: Project root ready.
Example 2: Write api/package.json
Type this:
printf '%s\n' '{' ' "name": "fest-api",' ' "version": "1.0.0",' ' "main": "server.js",' ' "dependencies": {' ' "express": "4.19.2",' ' "pg": "8.12.0"' ' }' '}' > api/package.json && wc -l api/package.json
You will see:
10 api/package.json
What it means: Express and pg driver.
Example 3: Write api/server.js
Type this:
printf '%s\n' 'const express = require("express");' 'const { Pool } = require("pg");' 'const app = express();' 'app.use(express.json());' 'const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });' 'app.get("/healthz", async (_,res) => { await pool.query("SELECT 1"); res.json({ ok: true }); });' 'app.get("/api/events", async (_,res) => {' ' const { rows } = await pool.query("SELECT id, title, venue, seats_left FROM events ORDER BY id");' ' res.json(rows);' '});' 'app.post("/api/events/:id/register", async (req,res) => {' ' const { rows } = await pool.query("UPDATE events SET seats_left = seats_left - 1 WHERE id=$1 AND seats_left > 0 RETURNING id, seats_left", [req.params.id]);' ' if (!rows.length) return res.status(409).json({ error: "full" });' ' res.json({ registered: true, seats_left: rows[0].seats_left });' '});' 'process.on("SIGTERM", async () => { await pool.end(); process.exit(0); });' 'app.listen(3000, () => console.log("fest-api on 3000"));' > api/server.js && wc -l api/server.js
You will see:
18 api/server.js
What it means: Health, list and atomic register.
Step 2: API Dockerfile and seed SQL
Why: Non-root Node image.
What: npm ci in the image. init.sql seeds three events.
Example 4: Write api/Dockerfile
Type this:
printf '%s\n' 'FROM node:20-alpine' 'WORKDIR /app' 'COPY package.json .' 'RUN npm install --omit=dev' 'COPY server.js .' 'USER node' 'EXPOSE 3000' 'HEALTHCHECK CMD wget -qO- http://127.0.0.1:3000/healthz || exit 1' 'CMD ["node","server.js"]' > api/Dockerfile && wc -l api/Dockerfile
You will see:
9 api/Dockerfile
What it means: Alpine Node as user node with healthcheck.
Example 5: Write db/init.sql
Type this:
printf '%s\n' 'CREATE TABLE events (' ' id SERIAL PRIMARY KEY,' ' title TEXT NOT NULL,' ' venue TEXT NOT NULL,' ' seats_left INT NOT NULL' ');' 'INSERT INTO events (title, venue, seats_left) VALUES' ' ("Robotics Workshop", "Lab 2", 40),' ' ("Battle of Bands", "Main Ground", 500),' ' ("Hackathon", "Library Hall", 2);' > db/init.sql && wc -l db/init.sql
You will see:
10 db/init.sql
What it means: Three fest events seeded.
Example 6: Show atomic update
Type this:
grep seats_left api/server.js | head -1
You will see:
const { rows } = await pool.query("UPDATE events SET seats_left = seats_left - 1 WHERE id=$1 AND seats_left > 0 RETURNING id, seats_left", [req.params.id]);
What it means: Two students cannot take the last seat twice.
3. React frontend and nginx
Step 3: Minimal React with Vite build files
Why: Classroom without create-react-app download fights.
What: We write a tiny Vite React app by hand: index.html, main.jsx, package.json. The multi-stage image builds dist/ then copies into nginx.
Example 7: Write web/package.json
Type this:
printf '%s\n' '{' ' "name": "fest-web",' ' "private": true,' ' "version": "1.0.0",' ' "type": "module",' ' "scripts": { "build": "vite build", "dev": "vite --host 0.0.0.0 --port 5173" },' ' "dependencies": { "react": "18.3.1", "react-dom": "18.3.1" },' ' "devDependencies": { "vite": "5.4.8", "@vitejs/plugin-react": "4.3.2" }' '}' > web/package.json && wc -l web/package.json
You will see:
12 web/package.json
What it means: React 18 and Vite.
Example 8: Write web files
Type this:
printf '%s\n' '<!doctype html><html><head><meta charset="UTF-8"/><title>Pune College Fest</title></head>' '<body><div id="root"></div><script type="module" src="/src/main.jsx"></script></body></html>' > web/index.html
printf '%s\n' 'import { defineConfig } from "vite";' 'import react from "@vitejs/plugin-react";' 'export default defineConfig({ plugins: [react()], server: { proxy: { "/api": "http://api:3000" } } });' > web/vite.config.js
printf '%s\n' 'import React, { useEffect, useState } from "react";' 'import { createRoot } from "react-dom/client";' 'function App(){' ' const [events,setEvents]=useState([]);' ' useEffect(()=>{ fetch("/api/events").then(r=>r.json()).then(setEvents); },[]);' ' return (<div><h1>Pune College Fest</h1><ul>{events.map(e=>' ' <li key={e.id}>{e.title} at {e.venue} ({e.seats_left} seats)' ' <button onClick={()=>fetch(`/api/events/${e.id}/register`,{method:"POST"}).then(()=>fetch("/api/events").then(r=>r.json()).then(setEvents))}>Register</button></li>)}</ul></div>);' '}' 'createRoot(document.getElementById("root")).render(<App/>);' > web/src/main.jsx && wc -l web/src/main.jsx
You will see:
10 web/src/main.jsx
What it means: Fetches /api/events and registers.
Example 9: Write web Dockerfile
Type this:
printf '%s\n' 'FROM node:20-alpine AS build' 'WORKDIR /web' 'COPY package.json .' 'RUN npm install' 'COPY . .' 'RUN npm run build' '' 'FROM nginx:1.27-alpine' 'COPY --from=build /web/dist /usr/share/nginx/html' 'COPY nginx.conf /etc/nginx/conf.d/default.conf' 'EXPOSE 80' > web/Dockerfile && wc -l web/Dockerfile
You will see:
10 web/Dockerfile
What it means: Stage 1 builds; stage 2 is nginx only.
Step 4: nginx proxy config
Why: Same origin for browser.
What: The browser calls /api/... on the same host. nginx proxies to api:3000. SPA fallback serves index.html for client routes.
Example 10: Write web/nginx.conf
Type this:
printf '%s\n' 'server {' ' listen 80;' ' root /usr/share/nginx/html;' ' location /api/ {' ' proxy_pass http://api:3000/api/;' ' proxy_http_version 1.1;' ' proxy_set_header Host $host;' ' }' ' location / {' ' try_files $uri /index.html;' ' }' '}' > web/nginx.conf && grep proxy_pass web/nginx.conf
You will see:
proxy_pass http://api:3000/api/;
What it means: /api goes to the Node service.
Example 11: Show SPA fallback
Type this:
grep try_files web/nginx.conf
You will see:
try_files $uri /index.html;
What it means: Refresh on /events/3 still loads React.
Example 12: Why same origin
Type this:
echo 'No CORS needed because browser sees one host'
You will see:
No CORS needed because browser sees one host
What it means: nginx hides the API port.
4. Compose all tiers
Step 5: Production Compose
Why: Three services.
What: Publish only web:8080. Database stays on the internal network.
Example 13: Write compose.yaml
Type this:
printf '%s\n' 'name: fest' 'services:' ' db:' ' image: postgres:16-alpine' ' environment:' ' POSTGRES_DB: fest' ' POSTGRES_USER: fest' ' POSTGRES_PASSWORD: ${DB_PASSWORD}' ' volumes: [pg-data:/var/lib/postgresql/data, ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro]' ' healthcheck:' ' test: ["CMD-SHELL", "pg_isready -U fest -d fest"]' ' interval: 5s' ' retries: 20' ' networks: [back]' '' ' api:' ' build: ./api' ' environment:' ' DATABASE_URL: postgres://fest:${DB_PASSWORD}@db:5432/fest' ' depends_on:' ' db: {condition: service_healthy}' ' networks: [front, back]' '' ' web:' ' build: ./web' ' ports: ["8080:80"]' ' depends_on: [api]' ' networks: [front]' '' 'networks: {front:, back:}' 'volumes: {pg-data:}' > compose.yaml
printf '%s\n' 'DB_PASSWORD=fest-pass' > .env && wc -l compose.yaml
You will see:
36 compose.yaml
What it means: front and back networks.
Example 14: Start and health
Type this:
docker compose up -d --build
sleep 10
curl -s http://localhost:8080/api/healthz 2>/dev/null || curl -s http://localhost:8080/../api/healthz
curl -s http://localhost:8080/api/events | head -c 160
You will see:
[{"id":1,"title":"Robotics Workshop","venue":"Lab 2","seats_left":40}
What it means: API through nginx returns events.
Example 15: Register last Hackathon seats
Type this:
curl -s -X POST http://localhost:8080/api/events/3/register
curl -s -X POST http://localhost:8080/api/events/3/register
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8080/api/events/3/register
You will see:
{"registered":true,"seats_left":1}
{"registered":true,"seats_left":0}
409
What it means: Third register is full.
Step 6: Dev Compose overlay
Why: Hot reload.
What: compose.dev.yaml bind-mounts source and runs Vite. Use both files together.
Example 16: Write compose.dev.yaml
Type this:
printf '%s\n' 'services:' ' web:' ' image: node:20-alpine' ' working_dir: /web' ' command: sh -c "npm install && npm run dev"' ' volumes: [./web:/web]' ' ports: ["5173:5173"]' ' environment:' ' - CHOKIDAR_USEPOLLING=true' ' api:' ' volumes: [./api:/app]' ' command: sh -c "npm install && node server.js"' > compose.dev.yaml && wc -l compose.dev.yaml
You will see:
14 compose.dev.yaml
What it means: Dev overrides for web and api.
Example 17: How to start dev
Type this:
echo 'docker compose -f compose.yaml -f compose.dev.yaml up --build'
You will see:
docker compose -f compose.yaml -f compose.dev.yaml up --build
What it means: Vite on 5173 proxies /api.
Example 18: Prod stays multi-stage
Type this:
grep 'FROM nginx' web/Dockerfile
You will see:
FROM nginx:1.27-alpine
What it means: Production image has no Node.
5. Mistakes and clean up
Step 7: Common mistakes
Why: Publishing Postgres and skipping proxy.
What: Publishing 5432 on a laptop is a risk. Calling http://api:3000 from the browser fails because api is not on the host.
Example 19: Db not published
Type this:
grep -A6 'db:' compose.yaml | grep ports || echo 'no host ports on db'
You will see:
no host ports on db
What it means: Postgres only on back network.
Example 20: Browser uses /api
Type this:
grep fetch web/src/main.jsx | head -1
You will see:
useEffect(()=>{ fetch("/api/events").then(r=>r.json()).then(setEvents); },[]);
What it means: Relative /api path.
Example 21: SIGTERM closes pool
Type this:
grep SIGTERM api/server.js
You will see:
process.on("SIGTERM", async () => { await pool.end(); process.exit(0); });
What it means: Clean shutdown on docker stop.
Step 8: Clean up
Why: Stop and remove volumes.
What: down -v removes fest data.
Example 22: Stop stack
Type this:
docker compose down -v
You will see:
... Removed
What it means: fest project gone.
Example 23: Remove images
Type this:
docker image rm fest-web fest-api 2>/dev/null; echo done
You will see:
done
What it means: Build images removed.
Example 24: Code remains
Type this:
ls api web db | head
You will see:
api
db
web
What it means: Sources stay on the host.
Step 9: Why two networks
Why: Limit blast radius.
What: The browser reaches web. web reaches api. api reaches db. The browser never talks to Postgres.
Example 25: Show networks
Type this:
grep -E 'networks:|front|back' compose.yaml | head -10
You will see:
networks: [back]
networks: [front, back]
networks: [front]
networks: {front:, back:}
What it means: db only on back.
Example 26: web has no db env
Type this:
grep -A8 'web:' compose.yaml | grep DATABASE || echo 'web has no DATABASE_URL'
You will see:
web has no DATABASE_URL
What it means: Frontend never sees SQL credentials.
Example 27: Interview line
Type this:
echo 'three tiers: UI, API, data; proxy keeps one origin'
You will see:
three tiers: UI, API, data; proxy keeps one origin
What it means: Standard fest and ticket apps.
Step 10: Health before traffic
Why: API then UI.
What: Wait for Postgres healthy, API /healthz, then open the UI. Atomic register needs the seed rows.
Example 28: API health through proxy
Type this:
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/api/events
You will see:
200
What it means: Events endpoint ready when stack was up.
Example 29: Seed hackathon seats
Type this:
grep Hackathon db/init.sql
You will see:
("Hackathon", "Library Hall", 2);
What it means: Only two seats for the race demo.
Example 30: Pool max
Type this:
grep 'max: 10' api/server.js
You will see:
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
What it means: Caps open DB connections.
Step 11: Image sizes matter
Why: Drop Node from production web.
What: The build stage has npm. The final nginx stage is tens of megabytes. Shipping Vite to production would waste disk and attack surface.
Example 31: Show stages
Type this:
grep '^FROM' web/Dockerfile
You will see:
FROM node:20-alpine AS build
FROM nginx:1.27-alpine
What it means: Two stages.
Example 32: Final userland
Type this:
echo 'nginx alpine + static files only'
You will see:
nginx alpine + static files only
What it means: No node binary in prod web.
Example 33: API stays Node
Type this:
grep '^FROM' api/Dockerfile
You will see:
FROM node:20-alpine
What it means: API needs Node at runtime.
Step 12: CORS is a smell here
Why: Prefer same-origin proxy.
What: If the UI called http://localhost:3000 from http://localhost:8080 you would fight CORS. The proxy avoids that class of bugs.
Example 34: Relative fetch
Type this:
grep fetch web/src/main.jsx | head -1
You will see:
fetch("/api/events")
What it means: Relative URL.
Example 35: proxy_pass target
Type this:
grep proxy_pass web/nginx.conf
You will see:
proxy_pass http://api:3000/api/;
What it means: Container DNS name api.
Example 36: When CORS appears
Type this:
echo 'Only if a separate UI domain must call the API directly'
You will see:
Only if a separate UI domain must call the API directly
What it means: Then set deliberate CORS headers on the API.
Ravindra Bagale's Tip
Keep the browser on one origin with nginx proxying /api. BookMyShow-style apps and college fest portals avoid CORS pain this way.
nginx /api proxy करून browser एकाच origin वर ठेवा. BookMyShow-style apps आणि college fest portals यामुळे CORS दुखणे टाळतात.
nginx से /api proxy कर browser को एक ही origin पर रखें. BookMyShow-style apps और college fest portals इससे CORS दर्द से बचते हैं.
Check yourself
Q1. What are the three tiers here?
React UI in nginx, Node API, and PostgreSQL.
Q2. Why proxy /api through nginx?
So the browser uses one origin and needs no CORS.
Q3. How do two students not steal the last seat?
UPDATE ... WHERE seats_left > 0 RETURNING in one SQL statement.
Q4. What does the multi-stage web image remove?
The Node toolchain; only nginx plus dist/ remain.
Q5. Why is Postgres on the back network only?
So the database is not reachable from the browser or the public internet.
Q6. What is compose.dev.yaml for?
Hot reload with Vite and bind mounts during development.
Friends, you built a 3-tier fest app with React, Node and Postgres, proxied /api through nginx, and proved atomic seat registration. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and repeat the register calls until you see 409. Next chapter: cloud projects with AWS RDS, DynamoDB and S3.
मित्रांनो, आज तुम्ही React, Node आणि Postgres सह 3-tier fest app build केली, nginx ने /api proxy केले, आणि atomic seat registration सिद्ध केली. नसेल तर Picture 1 आणि 2 बघा आणि 409 येईपर्यंत register calls पुन्हा करा. पुढचा chapter: AWS RDS, DynamoDB आणि S3 सह cloud projects.
दोस्तों, आज आपने React, Node और Postgres के साथ 3-tier fest app build की, nginx से /api proxy किया, और atomic seat registration सिद्ध की. नहीं तो Picture 1 और 2 देखिए और 409 आने तक register calls दोहराइए. अगला chapter: AWS RDS, DynamoDB और S3 के साथ cloud projects.
Lab: try at home
- Write the Node API with atomic register.
- Seed Postgres with three events.
- Write the Vite React app and multi-stage Dockerfile.
- Add nginx.conf with /api proxy and SPA fallback.
- Start compose.yaml and list events through port 8080.
- Register until Hackathon returns 409.
- Try the dev overlay idea, then clean up.
Recap
- Three tiers: UI, API, data.
- nginx serves React and proxies /api.
- Postgres stays on a private network.
- Atomic SQL protects the last seat.
- Multi-stage builds drop the Node toolchain.
- Dev overlays add hot reload.
Lab
- Finish every project in this chapter on one Ubuntu VM or laptop.
- Keep each project in its own folder.
- Run docker compose down -v after each project.
- Write the commands you typed in a notebook.
- Break one thing on purpose in each project and fix it.
Practice task
Pick any two projects and combine them behind one nginx container on ports 80 and 8080.
Ravindra Bagale's Tip
A project you never ran does not teach Docker. Do one project every day, and show its demo in the interview.
न चालवलेला project Docker शिकवत नाही. रोज एक project करा, आणि interview मध्ये त्याचा demo दाखवा.
न चलाया हुआ project Docker नहीं सिखाता. रोज़ एक project कीजिए, और interview में उसका demo दिखाइए.
In short
- Every project follows the same order: code, Dockerfile, compose, run, test, clean.
- Data lives in named volumes.
- Containers talk by service name on a user-defined network.
- Secrets come from .env files that never go to Git.
Revision card
Interview card