Ravindra BagaleCourses & study guides मराठी

Chapter 57: Docker Projects Part 1: Websites, Databases, LAMP, LEMP, WordPress, 3-Tier and Every Language with MySQL and MongoDB

DevOps

57.2 Project 2: Todo app with Node.js and MySQL (Compose getting-started style)

Friends, today we build a real todo app. Node.js talks to MySQL. Both run as containers. One compose file starts everything. Data survives restarts. We test the API, look at tables in Adminer, break MySQL on purpose, fix it, and clean up. Type every command yourself.

What you will learn in this lesson

  1. Why an app and a database belong together in Compose.
  2. How a Node.js API reaches MySQL by service name.
  3. How named volumes keep data after a restart.
  4. How health checks make the app wait for MySQL.
  5. How Adminer lets you see the tables in a browser.

1. Start from a real problem

Suppose we join Infosys as freshers. The first task is a small internal todo app for our team. The app is Node.js with Express. The data must live in MySQL.

On a normal laptop we install Node 20, install MySQL 8, create a user, create a database, and fix the root password three times. A teammate on Windows gets different errors.

With Docker Compose the app and the database are two containers in one file. Anyone runs docker compose up and gets the same Node version, the same MySQL version and the same data setup. Companies like Flipkart and Swiggy use this pattern for local developer setups every day.

app (Node.js)REST API on door 3000db (MySQL 8)stores todos in a volumeadminerbrowser UI for the tablesCompose networkapp reaches db by name
Picture 1: three containers, one network

2. Prepare the project folder

Step 1: Project folder

Why: A clean place for every file.

What: Keep each project in its own folder. The app code, the Dockerfile, the SQL init script, Compose and the env file all live here.

Example 1: Make the folders

Type this:

mkdir -p todo-app/src todo-app/db && cd todo-app && pwd

You will see:

/home/you/todo-app

What it means: You are inside the project folder.

Example 2: See the empty tree

Type this:

find . -type d | sort

You will see:

.
./db
./src

What it means: Two empty folders wait for code and SQL.

Example 3: Check Compose is installed

Type this:

docker compose version

You will see:

Docker Compose version v2.29.7

What it means: Compose v2 is ready. If the command fails, install the Compose plugin first.

3. Write the Node.js API

Step 2: package.json

Why: List the libraries the app needs.

What: package.json names the app and its dependencies. express is the web framework. mysql2 talks to MySQL with a connection pool.

Example 4: Write package.json

Type this:

printf '%s\n' '{' '  "name": "todo-app",' '  "version": "1.0.0",' '  "main": "src/index.js",' '  "scripts": { "start": "node src/index.js" },' '  "dependencies": {' '    "express": "^4.21.1",' '    "mysql2": "^3.11.3"' '  }' '}' > package.json && wc -l package.json

You will see:

11 package.json

What it means: Eleven lines. Two libraries only.

Example 5: Show the dependency names

Type this:

grep -E 'express|mysql2' package.json

You will see:

"express": "^4.21.1",
"mysql2": "^3.11.3"

What it means: Exact packages the Dockerfile will install.

Example 6: Create the lock file with a one-shot container

Type this:

docker run --rm -v "$PWD":/app -w /app node:20-alpine npm install --package-lock-only

You will see:

added 70 packages, and audited 70 packages in 3s

What it means: package-lock.json now exists. npm ci can use exact versions during the image build.

Step 3: src/index.js

Why: The API that talks to MySQL.

What: The app creates a pool to MySQL, exposes health, list, add, mark-done and delete routes, and listens on port 3000. The host name db is the Compose service name.

Example 7: Write the API file

Type this:

printf '%s\n' 'const express = require("express");' 'const mysql = require("mysql2/promise");' '' 'const pool = mysql.createPool({' '  host: process.env.DB_HOST || "db",' '  user: process.env.DB_USER,' '  password: process.env.DB_PASSWORD,' '  database: process.env.DB_NAME,' '  connectionLimit: 5' '});' '' 'const app = express();' 'app.use(express.json());' '' 'app.get("/healthz", async (req, res) => {' '  try { await pool.query("SELECT 1"); res.send("ok"); }' '  catch (e) { res.status(500).send("db down"); }' '});' '' 'app.get("/api/todos", async (req, res) => {' '  const [rows] = await pool.query("SELECT id, title, done FROM todos ORDER BY id");' '  res.json(rows);' '});' '' 'app.post("/api/todos", async (req, res) => {' '  const title = (req.body.title || "").trim();' '  if (!title) return res.status(400).json({ error: "title is required" });' '  const [r] = await pool.query("INSERT INTO todos (title) VALUES (?)", [title]);' '  res.status(201).json({ id: r.insertId, title, done: 0 });' '});' '' 'app.patch("/api/todos/:id/done", async (req, res) => {' '  await pool.query("UPDATE todos SET done = 1 WHERE id = ?", [req.params.id]);' '  res.json({ id: Number(req.params.id), done: 1 });' '});' '' 'app.delete("/api/todos/:id", async (req, res) => {' '  await pool.query("DELETE FROM todos WHERE id = ?", [req.params.id]);' '  res.status(204).end();' '});' '' 'const port = process.env.PORT || 3000;' 'app.listen(port, () => console.log("todo app listening on " + port));' > src/index.js && wc -l src/index.js

You will see:

42 src/index.js

What it means: Forty-two lines. Full REST API in one file.

Example 8: Show the MySQL host line

Type this:

grep -A2 'createPool' src/index.js | head -4

You will see:

const pool = mysql.createPool({
  host: process.env.DB_HOST || "db",

What it means: Default host is db, the Compose service name.

Example 9: Show the health route

Type this:

grep -A3 'healthz' src/index.js | head -4

You will see:

app.get("/healthz", async (req, res) => {
  try { await pool.query("SELECT 1"); res.send("ok"); }

What it means: Health is ok only when MySQL answers SELECT 1.

4. Dockerfile for the app

Step 4: App Dockerfile

Why: Same Node version everywhere.

What: The Dockerfile starts from node:20-alpine, installs production packages with npm ci, copies the source, runs as the non-root node user, and adds a health check.

Example 10: Write the Dockerfile

Type this:

printf '%s\n' 'FROM node:20-alpine' 'WORKDIR /app' 'ENV NODE_ENV=production' 'COPY package*.json ./' 'RUN npm ci --omit=dev' 'COPY src/ ./src/' 'USER node' 'EXPOSE 3000' 'HEALTHCHECK --interval=10s --timeout=3s --retries=5 CMD wget -qO- http://localhost:3000/healthz || exit 1' 'CMD ["node", "src/index.js"]' > Dockerfile && wc -l Dockerfile

You will see:

10 Dockerfile

What it means: Ten lines. Copy package files first so dependency layers cache.

Example 11: Write .dockerignore

Type this:

printf '%s\n' 'node_modules' '.env' '*.log' > .dockerignore && cat .dockerignore

You will see:

node_modules
.env
*.log

What it means: Local node_modules and secrets never enter the build context.

Example 12: Count important lines

Type this:

grep -cE '^(FROM|USER|HEALTHCHECK|CMD)' Dockerfile

You will see:

4

What it means: Base image, non-root user, health check and start command are all set.

Step 5: Why each Dockerfile line matters

Why: Read before you build.

What: COPY package files before source so a code change does not reinstall packages. USER node stops the process from running as root. HEALTHCHECK tells Compose when the app is ready.

Example 13: Show the cache-friendly copy

Type this:

grep -n 'COPY package' Dockerfile

You will see:

4:COPY package*.json ./

What it means: Layer 4 holds packages. Source copy comes later.

Example 14: Show the non-root user

Type this:

grep '^USER' Dockerfile

You will see:

USER node

What it means: The node user already exists in the official image.

Example 15: Show the health check

Type this:

grep HEALTHCHECK Dockerfile

You will see:

HEALTHCHECK --interval=10s --timeout=3s --retries=5 CMD wget -qO- http://localhost:3000/healthz || exit 1

What it means: Compose and Docker both use this to mark the app healthy.

5. MySQL init and Compose

Empty named volumetodo-mysqlMySQL first bootruns /docker-entrypoint-initdb.d/*.sqltodos table readyapp can INSERT and SELECT
Picture 2: first start of MySQL

Step 6: db/init.sql

Why: Create the table on first start.

What: MySQL official images run every .sql file in /docker-entrypoint-initdb.d the first time an empty volume starts. After that the volume already has data, so init does not run again.

Example 16: Write the init SQL

Type this:

printf '%s\n' 'CREATE TABLE IF NOT EXISTS todos (' '  id INT AUTO_INCREMENT PRIMARY KEY,' '  title VARCHAR(200) NOT NULL,' '  done TINYINT(1) NOT NULL DEFAULT 0,' '  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP' ');' > db/init.sql && cat db/init.sql

You will see:

CREATE TABLE IF NOT EXISTS todos (
  id INT AUTO_INCREMENT PRIMARY KEY,
  ...

What it means: One table with id, title, done and created_at.

Example 17: Count columns

Type this:

grep -cE 'id|title|done|created' db/init.sql

You will see:

4

What it means: Four columns as planned.

Example 18: Confirm IF NOT EXISTS

Type this:

grep 'IF NOT EXISTS' db/init.sql

You will see:

CREATE TABLE IF NOT EXISTS todos (

What it means: Safe to re-run if someone mounts the script again.

Step 7: compose.yaml

Why: One file for app, db and Adminer.

What: Compose describes three services, one named volume and a user-defined network. The app waits until MySQL is healthy. Passwords come from an env file.

Example 19: Write compose.yaml

Type this:

printf '%s\n' 'services:' '  db:' '    image: mysql:8.4' '    environment:' '      MYSQL_DATABASE: todos' '      MYSQL_USER: todo' '      MYSQL_PASSWORD: ${DB_PASSWORD}' '      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}' '    volumes:' '      - todo-mysql:/var/lib/mysql' '      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro' '    healthcheck:' '      test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-uroot", "-p${DB_ROOT_PASSWORD}"]' '      interval: 5s' '      timeout: 5s' '      retries: 20' '    restart: unless-stopped' '' '  app:' '    build: .' '    ports:' '      - "3000:3000"' '    environment:' '      DB_HOST: db' '      DB_USER: todo' '      DB_PASSWORD: ${DB_PASSWORD}' '      DB_NAME: todos' '    depends_on:' '      db:' '        condition: service_healthy' '    restart: unless-stopped' '' '  adminer:' '    image: adminer:4' '    ports:' '      - "8080:8080"' '    depends_on:' '      db:' '        condition: service_healthy' '    restart: unless-stopped' '' 'volumes:' '  todo-mysql:' > compose.yaml && wc -l compose.yaml

You will see:

42 compose.yaml

What it means: Forty-two lines. Three services and one volume.

Example 20: Write .env and .gitignore

Type this:

printf '%s\n' 'DB_PASSWORD=todo-pass-change-me' 'DB_ROOT_PASSWORD=root-pass-change-me' > .env
printf '%s\n' '.env' 'node_modules/' '*.log' > .gitignore && cat .gitignore

You will see:

.env
node_modules/
*.log

What it means: Secrets stay in .env. Git ignores that file.

Example 21: Show how the app waits

Type this:

grep -A3 'depends_on' compose.yaml | head -4

You will see:

depends_on:
  db:
    condition: service_healthy

What it means: The app starts only after MySQL health passes.

6. Start and test

Step 8: docker compose up

Why: Build and start everything.

What: One command builds the app image, pulls MySQL and Adminer, creates the volume, runs init.sql, waits for healthy, then starts the app.

Example 22: Start the stack

Type this:

docker compose up -d --build

You will see:

[+] Building ... FINISHED
[+] Running 4/4
 ✔ Network todo-app_default    Created
 ✔ Volume todo-app_todo-mysql  Created
 ✔ Container todo-app-db-1     Healthy
 ✔ Container todo-app-app-1    Started

What it means: Four resources. db became Healthy before app started.

Example 23: See service status

Type this:

docker compose ps

You will see:

NAME              IMAGE         STATUS                   PORTS
todo-app-db-1     mysql:8.4     Up 40 seconds (healthy)  3306/tcp
todo-app-app-1    todo-app-app  Up 20 seconds (healthy)  0.0.0.0:3000->3000/tcp
todo-app-adminer-1 adminer:4    Up 20 seconds            0.0.0.0:8080->8080/tcp

What it means: All three are up. Both health checks passed.

Example 24: Hit the health URL

Type this:

curl -s http://localhost:3000/healthz

You will see:

ok

What it means: The app reached MySQL and answered ok.

Step 9: Use the REST API

Why: Add, list, done and delete.

What: curl sends the same HTTP calls a browser or a mobile app would send. We prove every route works.

Example 25: Add two todos

Type this:

curl -s -X POST http://localhost:3000/api/todos -H 'Content-Type: application/json' -d '{"title":"Buy milk"}'
curl -s -X POST http://localhost:3000/api/todos -H 'Content-Type: application/json' -d '{"title":"Ship release"}'

You will see:

{"id":1,"title":"Buy milk","done":0}
{"id":2,"title":"Ship release","done":0}

What it means: Two rows inserted. Ids 1 and 2.

Example 26: List and mark done

Type this:

curl -s http://localhost:3000/api/todos
curl -s -X PATCH http://localhost:3000/api/todos/1/done

You will see:

[{"id":1,"title":"Buy milk","done":0},{"id":2,"title":"Ship release","done":0}]
{"id":1,"done":1}

What it means: List works. Todo 1 is now done.

Example 27: Delete and list again

Type this:

curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://localhost:3000/api/todos/2
curl -s http://localhost:3000/api/todos

You will see:

204
[{"id":1,"title":"Buy milk","done":1}]

What it means: 204 means deleted. Only todo 1 remains.

Step 10: Look with Adminer

Why: See the same data in a browser UI.

What: Adminer is a tiny PHP page that talks to MySQL. Open http://localhost:8080, choose MySQL, server db, user todo, the password from .env, database todos.

Example 28: Confirm Adminer answers

Type this:

curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/

You will see:

200

What it means: Adminer is reachable on door 8080.

Example 29: Query from the db container

Type this:

docker compose exec -e MYSQL_PWD=todo-pass-change-me db mysql -utodo todos -e 'SELECT id,title,done FROM todos;'

You will see:

id  title   done
1   Buy milk    1

What it means: Same row Adminer will show. Server name inside the network is db.

Example 30: Show the volume

Type this:

docker volume ls | grep todo

You will see:

local     todo-app_todo-mysql

What it means: Named volume holds /var/lib/mysql for real.

7. Prove data survives and fix failures

Step 11: Restart keeps the data

Why: Volumes outlive containers.

What: If we recreate the app and db containers, the named volume still has the todos table and our row.

Example 31: Recreate containers

Type this:

docker compose up -d --force-recreate
sleep 15
curl -s http://localhost:3000/api/todos

You will see:

[{"id":1,"title":"Buy milk","done":1}]

What it means: Row is still there after recreate.

Example 32: Stop and start again

Type this:

docker compose down
docker compose up -d
sleep 20
curl -s http://localhost:3000/api/todos

You will see:

[{"id":1,"title":"Buy milk","done":1}]

What it means: down without -v keeps the volume. Data survived.

Example 33: What -v would do

Type this:

docker compose down --help | grep -A1 -- '-v,'

You will see:

-v, --volumes  Remove named volumes declared in the volumes section.

What it means: Only down -v deletes todo-mysql. Use it at cleanup, not during practice.

Step 12: Break MySQL on purpose

Why: See the health check catch it.

What: Stop the db container. The app health becomes unhealthy because SELECT 1 fails. Start db again and the app recovers.

Example 34: Stop the database

Type this:

docker compose stop db
sleep 12
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/healthz
docker inspect -f '{{.State.Health.Status}}' todo-app-app-1

You will see:

500
unhealthy

What it means: Health URL says db down. Docker marks the app unhealthy.

Example 35: Start db again

Type this:

docker compose start db
sleep 25
curl -s http://localhost:3000/healthz
docker inspect -f '{{.State.Health.Status}}' todo-app-app-1

You will see:

ok
healthy

What it means: MySQL is back. App is healthy again.

Example 36: Read recent app logs

Type this:

docker compose logs --tail 8 app

You will see:

todo app listening on 3000
...

What it means: Logs show the listen line and any connection errors while db was down.

Step 13: Common mistakes

Why: Fix them fast.

What: Wrong password, missing lock file, and port clashes are the three errors beginners hit first.

Example 37: Wrong DB password symptom

Type this:

docker compose logs app 2>&1 | grep -i 'access denied' || echo 'no access-denied line right now'

You will see:

no access-denied line right now

What it means: If you mistype DB_PASSWORD in .env you will see Access denied for user. Fix .env and recreate.

Example 38: Port 3000 already taken

Type this:

docker run --rm -p 3000:3000 alpine true 2>&1 | head -2 || true

You will see:

docker: Error response from daemon: Bind for 0.0.0.0:3000 failed: port is already allocated.

What it means: Our Compose app owns 3000. Stop it or pick another host port.

Example 39: Missing package-lock

Type this:

ls package-lock.json && echo lock-ok

You will see:

package-lock.json
lock-ok

What it means: Without this file, npm ci fails during docker build. We created it earlier.

8. Clean up

Step 14: Remove the stack and the volume

Why: Leave the machine tidy.

What: down -v removes containers, the network and the named volume. Images can be removed next if you want disk space back.

Example 40: Stop and delete volume

Type this:

docker compose down -v

You will see:

Container todo-app-app-1  Removed
Container todo-app-db-1  Removed
Container todo-app-adminer-1  Removed
Volume todo-app_todo-mysql  Removed
Network todo-app_default  Removed

What it means: Everything from this project is gone.

Example 41: Remove the app image

Type this:

docker image rm todo-app-app 2>/dev/null || docker images | grep todo || echo 'image already gone'

You will see:

Untagged: todo-app-app:latest
Deleted: sha256:...

What it means: Project image removed.

Example 42: Confirm no todo containers

Type this:

docker ps -a --filter name=todo-app --format '{{.Names}}' | wc -l

You will see:

0

What it means: Zero leftover containers.

Ravindra Bagale's Tip

Never put real passwords in compose.yaml. Keep them in .env and add .env to .gitignore. In companies like TCS and Accenture, secrets come from a vault, not from a file in Git.

Check yourself

Q1. Why is the MySQL host named db in the app?

db is the Compose service name. Docker DNS resolves it to the MySQL container IP.

Q2. What does depends_on with condition service_healthy do?

Compose starts the app only after the db health check passes.

Q3. How does the todos table appear automatically?

MySQL runs db/init.sql from /docker-entrypoint-initdb.d on the first start of an empty volume.

Q4. How do you keep data after docker compose down?

Do not pass -v. The named volume todo-mysql stays on disk.

Q5. What does the app /healthz route check?

It runs SELECT 1 on MySQL. If that fails, the route returns 500 and Docker marks the app unhealthy.

Q6. Why copy package*.json before the source in the Dockerfile?

So dependency layers stay cached when only the source code changes.

Friends, you built a full todo stack today: Node API, MySQL with init SQL, named volume, health waits, Adminer, restart proof, break-and-fix, and clean up. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 again and type every command from the project folder step yourself. Next project: database containers with backups and admin UIs.

Lab: try at home

  1. Create todo-app with src and db folders.
  2. Write package.json, src/index.js and create package-lock.json.
  3. Write the Dockerfile and .dockerignore.
  4. Write db/init.sql, compose.yaml and .env.
  5. Start with docker compose up -d --build and hit /healthz.
  6. Add, list, done and delete todos with curl.
  7. Recreate containers and prove the row remains.
  8. Stop db, watch unhealthy, start db, watch healthy.
  9. Clean up with docker compose down -v.

Recap

  • Compose runs the app and MySQL with one command.
  • The app reaches MySQL by the service name db.
  • A named volume keeps data after restarts.
  • Init SQL runs only on the first empty volume start.
  • Health checks make the app wait for MySQL.
  • Adminer shows the same tables in a browser.
  • down -v deletes the volume; down alone keeps it.

Ravi Sir's Cards for this lesson

मराठी cards