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.3 Project 3: Database containers: MySQL, PostgreSQL, MongoDB and Redis with backups and admin UIs

Friends, today we run four databases as containers: MySQL, PostgreSQL, MongoDB and Redis. Each has a pinned version, a named volume, an init script, a health check and a backup. We restore one backup on purpose to prove it works. Type every command yourself.

What you will learn in this lesson

  1. Why every database runs as a pinned container with a named volume.
  2. How init scripts seed tables and documents on first start.
  3. How to bind ports to 127.0.0.1 so only your laptop can reach them.
  4. How to take a logical backup and prove a restore.
  5. How Adminer, mongo-express and RedisInsight help you look inside.

1. Start from a real problem

Suppose we are on the platform team at Swiggy. Every developer needs MySQL for orders, PostgreSQL for payments, MongoDB for restaurant menus and Redis for the cart.

Installing four database servers on every laptop takes a full day and breaks the laptop. Different versions cause bugs that only one person can see.

With Docker each database is one container with a pinned version, data in a named volume, and first-time setup in an init script. Flipkart and Zomato teams use the same idea for local stacks.

MySQL 8.4orders + AdminerPostgreSQL 16payments + AdminerMongoDB 7menus + mongo-expressRedis 7cart + RedisInsight
Picture 1: four databases, four volumes

2. Project folder and secrets

Step 1: Project folder

Why: One place for all four databases.

What: A single folder holds env values, init scripts and Compose. Keep passwords in .env, never in compose.yaml.

Example 1: Make folders

Type this:

mkdir -p dbs/init/mysql dbs/init/postgres dbs/init/mongo dbs/backups && cd dbs && pwd

You will see:

/home/you/dbs

What it means: Folders for init scripts and backup files are ready.

Example 2: Write .env

Type this:

printf '%s\n' 'MYSQL_ROOT_PASSWORD=change-me-mysql-root' 'MYSQL_PASSWORD=change-me-orders' 'POSTGRES_PASSWORD=change-me-payments' 'MONGO_ROOT_PASSWORD=change-me-mongo' 'REDIS_PASSWORD=change-me-redis' > .env && wc -l .env

You will see:

5 .env

What it means: Five placeholder passwords. Change them on a shared machine.

Example 3: Ignore secrets in Git

Type this:

printf '%s\n' '.env' 'backups/' > .gitignore && cat .gitignore

You will see:

.env
backups/

What it means: Passwords and dump files stay off Git.

3. Init scripts

Step 2: MySQL and Postgres init SQL

Why: Seed relational tables once.

What: Official MySQL and Postgres images run every file in /docker-entrypoint-initdb.d when the data volume is empty. After that the volume already has data, so init does not run again.

Example 4: Write MySQL init

Type this:

printf '%s\n' 'CREATE TABLE orders (' '  id INT AUTO_INCREMENT PRIMARY KEY,' '  restaurant VARCHAR(100) NOT NULL,' '  amount DECIMAL(8,2) NOT NULL,' '  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP' ');' 'INSERT INTO orders (restaurant, amount) VALUES ("Vaishali", 240.00), ("Goodluck Cafe", 180.50);' > init/mysql/01-orders.sql && wc -l init/mysql/01-orders.sql

You will see:

7 init/mysql/01-orders.sql

What it means: Orders table with two Pune restaurant rows.

Example 5: Write Postgres init

Type this:

printf '%s\n' 'CREATE TABLE payments (' '  id SERIAL PRIMARY KEY,' '  order_id INT NOT NULL,' '  method TEXT NOT NULL,' '  paid_at TIMESTAMPTZ DEFAULT now()' ');' 'INSERT INTO payments (order_id, method) VALUES (1, "UPI"), (2, "card");' > init/postgres/01-payments.sql && wc -l init/postgres/01-payments.sql

You will see:

7 init/postgres/01-payments.sql

What it means: Payments table with UPI and card rows.

Example 6: List init files

Type this:

find init -type f | sort

You will see:

init/mongo/01-menus.js
init/mysql/01-orders.sql
init/postgres/01-payments.sql

What it means: Three init files. Mongo comes next.

Step 3: Mongo init script

Why: Seed documents once.

What: MongoDB runs .js files from docker-entrypoint-initdb.d when the data folder is empty. We insert two restaurant menu documents.

Example 7: Write Mongo init

Type this:

printf '%s\n' 'db = db.getSiblingDB("menus");' 'db.restaurants.insertMany([' '  { name: "Vaishali", city: "Pune", items: ["Dosa", "SPDP", "Cold coffee"] },' '  { name: "Goodluck Cafe", city: "Pune", items: ["Bun maska", "Chai"] }' ']);' > init/mongo/01-menus.js && cat init/mongo/01-menus.js

You will see:

db = db.getSiblingDB("menus");
...

What it means: Two menu documents for Pune restaurants.

Example 8: Count insert targets

Type this:

grep -c 'name:' init/mongo/01-menus.js

You will see:

2

What it means: Two restaurants will be inserted.

Example 9: Show database name

Type this:

grep getSiblingDB init/mongo/01-menus.js

You will see:

db = db.getSiblingDB("menus");

What it means: Documents go into the menus database.

4. Compose with health and local ports

Container door 3306MySQL listens insideHost 127.0.0.1:3306only this laptop reaches itInternetcannot open the door
Picture 2: bind to localhost only

Step 4: compose.yaml databases

Why: Pinned images, volumes, health.

What: Pin every tag. Mount a named volume on the data directory. Publish ports as 127.0.0.1 so strangers on the network cannot connect. Add health checks so other services can wait.

Example 10: Write the four database services

Type this:

printf '%s\n' 'services:' '  mysql:' '    image: mysql:8.4' '    environment:' '      MYSQL_DATABASE: orders' '      MYSQL_USER: orders' '      MYSQL_PASSWORD: ${MYSQL_PASSWORD}' '      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}' '    ports: ["127.0.0.1:3306:3306"]' '    volumes:' '      - mysql-data:/var/lib/mysql' '      - ./init/mysql:/docker-entrypoint-initdb.d:ro' '    healthcheck:' '      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${MYSQL_ROOT_PASSWORD}"]' '      interval: 5s' '      retries: 20' '' '  postgres:' '    image: postgres:16-alpine' '    environment:' '      POSTGRES_DB: payments' '      POSTGRES_USER: payments' '      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}' '    ports: ["127.0.0.1:5432:5432"]' '    volumes:' '      - pg-data:/var/lib/postgresql/data' '      - ./init/postgres:/docker-entrypoint-initdb.d:ro' '    healthcheck:' '      test: ["CMD-SHELL", "pg_isready -U payments -d payments"]' '      interval: 5s' '      retries: 20' '' '  mongo:' '    image: mongo:7' '    environment:' '      MONGO_INITDB_ROOT_USERNAME: root' '      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_ROOT_PASSWORD}' '    ports: ["127.0.0.1:27017:27017"]' '    volumes:' '      - mongo-data:/data/db' '      - ./init/mongo:/docker-entrypoint-initdb.d:ro' '    healthcheck:' '      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand(\"ping\").ok"]' '      interval: 5s' '      retries: 20' '' '  redis:' '    image: redis:7-alpine' '    command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}"]' '    ports: ["127.0.0.1:6379:6379"]' '    volumes:' '      - redis-data:/data' '    healthcheck:' '      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]' '      interval: 5s' '      retries: 20' '' 'volumes:' '  mysql-data:' '  pg-data:' '  mongo-data:' '  redis-data:' > compose.yaml && wc -l compose.yaml

You will see:

55 compose.yaml

What it means: Four services, four volumes, all ports on 127.0.0.1.

Example 11: Count pinned images

Type this:

grep -E '^    image:' compose.yaml

You will see:

image: mysql:8.4
image: postgres:16-alpine
image: mongo:7
image: redis:7-alpine

What it means: No latest tags. Versions are pinned.

Example 12: Count localhost binds

Type this:

grep -c '127.0.0.1' compose.yaml

You will see:

4

What it means: All four database ports are laptop-only.

Step 5: Admin UI services

Why: Browse tables without a fat client.

What: Adminer talks to MySQL and Postgres. mongo-express talks to MongoDB. RedisInsight talks to Redis. Add them as more services on localhost ports.

Example 13: Append admin services

Type this:

printf '%s\n' '' '  adminer:' '    image: adminer:4' '    ports: ["127.0.0.1:8080:8080"]' '    depends_on:' '      mysql:' '        condition: service_healthy' '      postgres:' '        condition: service_healthy' '' '  mongo-express:' '    image: mongo-express:1.0.2-20' '    ports: ["127.0.0.1:8081:8081"]' '    environment:' '      ME_CONFIG_MONGODB_ADMINUSERNAME: root' '      ME_CONFIG_MONGODB_ADMINPASSWORD: ${MONGO_ROOT_PASSWORD}' '      ME_CONFIG_MONGODB_URL: mongodb://root:${MONGO_ROOT_PASSWORD}@mongo:27017/' '    depends_on:' '      mongo:' '        condition: service_healthy' '' '  redisinsight:' '    image: redis/redisinsight:latest' '    ports: ["127.0.0.1:5540:5540"]' '    depends_on:' '      redis:' '        condition: service_healthy' >> compose.yaml && grep -cE 'adminer:|mongo-express:|redisinsight:' compose.yaml

You will see:

3

What it means: Three admin UIs added on 8080, 8081 and 5540.

Example 14: Validate Compose file

Type this:

docker compose config --quiet && echo config-ok

You will see:

config-ok

What it means: YAML and env substitution are valid.

Example 15: Show admin ports

Type this:

grep -E '8080|8081|5540' compose.yaml

You will see:

ports: ["127.0.0.1:8080:8080"]
ports: ["127.0.0.1:8081:8081"]
ports: ["127.0.0.1:5540:5540"]

What it means: Admin UIs also bind to localhost only.

5. Start and verify seed data

Step 6: Start the stack

Why: One command, four healthy databases.

What: Compose pulls images, creates volumes, runs init scripts and waits until health checks pass.

Example 16: Start everything

Type this:

docker compose up -d

You will see:

[+] Running 11/11
 ✔ Volume dbs_mysql-data      Created
 ✔ Volume dbs_pg-data         Created
 ✔ Volume dbs_mongo-data      Created
 ✔ Volume dbs_redis-data      Created
 ✔ Container dbs-mysql-1      Healthy
 ✔ Container dbs-postgres-1   Healthy
 ✔ Container dbs-mongo-1      Healthy
 ✔ Container dbs-redis-1      Healthy

What it means: Volumes created. All four databases healthy.

Example 17: Service status

Type this:

docker compose ps --format 'table {{.Name}}\t{{.Status}}'

You will see:

NAME               STATUS
dbs-mysql-1        Up 40 seconds (healthy)
dbs-postgres-1     Up 40 seconds (healthy)
dbs-mongo-1        Up 40 seconds (healthy)
dbs-redis-1        Up 40 seconds (healthy)
dbs-adminer-1      Up 20 seconds
...

What it means: Health passed for every database.

Example 18: List volumes

Type this:

docker volume ls | grep dbs_

You will see:

local     dbs_mongo-data
local     dbs_mysql-data
local     dbs_pg-data
local     dbs_redis-data

What it means: Four named volumes hold the data files.

Step 7: Query each database

Why: Prove init scripts ran.

What: Use the client inside each container. You should see the seed rows and documents.

Example 19: MySQL orders

Type this:

docker compose exec -e MYSQL_PWD=change-me-orders mysql mysql -uorders orders -e 'SELECT id,restaurant,amount FROM orders;'

You will see:

id  restaurant  amount
1   Vaishali    240.00
2   Goodluck Cafe   180.50

What it means: Two order rows from the init SQL.

Example 20: Postgres payments

Type this:

docker compose exec -e PGPASSWORD=change-me-payments postgres psql -Upayments -dpayments -c 'SELECT id,order_id,method FROM payments;'

You will see:

 id | order_id | method
----+----------+--------
  1 |        1 | UPI
  2 |        2 | card

What it means: Two payment rows.

Example 21: Mongo menus and Redis ping

Type this:

docker compose exec mongo mongosh -u root -p change-me-mongo --quiet --eval 'db.getSiblingDB("menus").restaurants.countDocuments()'
docker compose exec redis redis-cli -a change-me-redis PING

You will see:

2
PONG

What it means: Two menu documents. Redis answers PONG.

6. Backups and restore test

Step 8: Logical backups

Why: Dump data to files.

What: A logical backup is SQL or archive text you can move and reload. Always store dumps outside the container.

Example 22: Backup MySQL

Type this:

docker compose exec -e MYSQL_PWD=change-me-mysql-root mysql mysqldump -uroot orders > backups/orders.sql && wc -l backups/orders.sql

You will see:

42 backups/orders.sql

What it means: orders.sql holds CREATE TABLE and INSERT statements.

Example 23: Backup Postgres

Type this:

docker compose exec -e PGPASSWORD=change-me-payments postgres pg_dump -Upayments payments > backups/payments.sql && wc -l backups/payments.sql

You will see:

55 backups/payments.sql

What it means: payments.sql is a full Postgres dump.

Example 24: Backup Mongo and Redis

Type this:

docker compose exec mongo mongodump -u root -p change-me-mongo --db menus --archive > backups/menus.archive
docker compose exec redis redis-cli -a change-me-redis SAVE
docker compose cp redis:/data/dump.rdb backups/dump.rdb
ls -la backups

You will see:

-rw-r--r-- ... dump.rdb
-rw-r--r-- ... menus.archive
-rw-r--r-- ... orders.sql
-rw-r--r-- ... payments.sql

What it means: Four backup files on the host.

Step 9: Restore test

Why: A backup is useless until you reload it.

What: We drop the MySQL orders data, reload from orders.sql, and prove the two restaurants return. Companies like PhonePe and Razorpay treat restore drills as mandatory.

Example 25: Wipe MySQL data

Type this:

docker compose exec -e MYSQL_PWD=change-me-orders mysql mysql -uorders orders -e 'DELETE FROM orders; SELECT COUNT(*) AS n FROM orders;'

You will see:

n
0

What it means: Table is empty. The backup must bring rows back.

Example 26: Restore from dump

Type this:

docker compose exec -T -e MYSQL_PWD=change-me-mysql-root mysql mysql -uroot orders < backups/orders.sql
docker compose exec -e MYSQL_PWD=change-me-orders mysql mysql -uorders orders -e 'SELECT COUNT(*) AS n FROM orders;'

You will see:

n
2

What it means: Two rows restored. The backup works.

Example 27: Show a restored restaurant

Type this:

docker compose exec -e MYSQL_PWD=change-me-orders mysql mysql -uorders orders -N -e 'SELECT restaurant FROM orders WHERE id=1;'

You will see:

Vaishali

What it means: Exact seed data is back.

7. Admin UIs and common mistakes

Step 10: Open the admin UIs

Why: See the same data in a browser.

What: Adminer at http://127.0.0.1:8080 uses server mysql or postgres. mongo-express is on 8081. RedisInsight is on 5540. All bind to localhost.

Example 28: Check Adminer

Type this:

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

You will see:

200

What it means: Adminer is up.

Example 29: Check mongo-express

Type this:

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

You will see:

200

What it means: mongo-express is up.

Example 30: Check RedisInsight

Type this:

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

You will see:

200

What it means: RedisInsight is up.

Step 11: Common mistakes

Why: Fix them before they hurt.

What: Using latest, publishing 0.0.0.0, and skipping restore tests are the three mistakes that bite teams.

Example 31: Reject latest for databases

Type this:

grep 'image:.*latest' compose.yaml | grep -v redisinsight || echo 'db-images-pinned'

You will see:

db-images-pinned

What it means: Database images stay pinned. Only the optional UI used latest here; pin that too in real work.

Example 32: Prove ports are localhost

Type this:

docker compose ps --format '{{.Name}} {{.Ports}}' | grep mysql

You will see:

dbs-mysql-1 127.0.0.1:3306->3306/tcp

What it means: Not 0.0.0.0. Only this machine can connect.

Example 33: Never skip restore

Type this:

ls backups/orders.sql && echo restore-already-proved

You will see:

backups/orders.sql
restore-already-proved

What it means: You already wiped and reloaded. Keep that habit.

8. Clean up

Step 12: Remove stack and volumes

Why: Leave no practice data behind.

What: down -v removes containers, networks and the four named volumes. Delete local backup files if you do not need them.

Example 34: Stop and delete volumes

Type this:

docker compose down -v

You will see:

Container ... Removed
Volume dbs_mysql-data  Removed
Volume dbs_pg-data  Removed
Volume dbs_mongo-data  Removed
Volume dbs_redis-data  Removed

What it means: All four volumes gone.

Example 35: Remove backup files

Type this:

rm -f backups/* && ls backups | wc -l

You will see:

0

What it means: Local dumps removed.

Example 36: Confirm no dbs containers

Type this:

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

You will see:

0

What it means: Clean machine.

Ravindra Bagale's Tip

A backup you never restored is a hope, not a backup. Every week restore one dump into a fresh volume. Teams at Amazon and Google run restore drills the same way.

Check yourself

Q1. Why pin mysql:8.4 instead of mysql:latest?

latest can change overnight and break the app. A pin keeps every laptop on the same version.

Q2. When do init scripts run?

Only on the first start of an empty data volume.

Q3. Why publish 127.0.0.1:3306:3306?

So only the local machine can reach MySQL, not other machines on the network.

Q4. What is a logical backup?

A dump of data as SQL or archive text, made with tools like mysqldump, pg_dump or mongodump.

Q5. How do you prove a backup works?

Wipe the data, restore from the dump file, and query the rows again.

Q6. Where should passwords live?

In .env, listed in .gitignore, never hard-coded in compose.yaml.

Friends, you ran four databases today with volumes, init scripts, localhost ports, admin UIs, backups and a real restore test. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 again and type the Compose and backup steps yourself. Next project: WordPress with MySQL, nginx and free HTTPS.

Lab: try at home

  1. Create the dbs folder with init and backups.
  2. Write .env and three init scripts.
  3. Write compose.yaml with four DBs and three admin UIs.
  4. Start and query seed data in each database.
  5. Take MySQL, Postgres, Mongo and Redis backups.
  6. Delete MySQL rows, restore, and prove two rows return.
  7. Open Adminer on localhost and browse a table.
  8. Clean up with docker compose down -v.

Recap

  • Pin every database image version.
  • Put data in named volumes.
  • Run init scripts only on empty volumes.
  • Bind ports to 127.0.0.1 for local practice.
  • Take logical backups to host files.
  • Always prove a restore.
  • Admin UIs help you see tables and keys.

Ravi Sir's Cards for this lesson

मराठी cards