Ravindra BagaleCourses & study guides मराठी

Chapter 58: Docker Projects Part 2: AWS RDS, DynamoDB, S3, Reel Upload, Microservices, Queues, Logging, Monitoring and Cloud Deploys

DevOps

58.1 Project 17: Every language in a container with AWS RDS MySQL (Node, Python, Go, Java, .NET, PHP)

Friends, today six languages talk to one MySQL. First we use a local MySQL container that looks like RDS. Then the same env vars point at real AWS RDS with an IAM role and no keys in code. Type every command yourself.

What you will learn in this lesson

  1. Why every language shares the same MYSQL_* env vars.
  2. How a local MySQL container mirrors RDS for free practice.
  3. How Node, Python, Go, Java, .NET and PHP connect.
  4. How an IAM role replaces hard-coded keys on EC2.
  5. How to clean up so the RDS bill stays zero.

1. Start from a real problem

Suppose Flipkart or Meesho runs order APIs in Node, Python, Go, Java, .NET and PHP, and every language must talk to one shared MySQL on AWS RDS.

Putting passwords in Git is how accounts get stolen. Practise on a local MySQL container first, then point the same env at RDS.

Infosys and Capgemini delivery teams teach the same rule: local MySQL first, then RDS with Secrets Manager or an IAM role.

Node Python GoJava .NET PHPMYSQL_HOST envsame for allSecurity group3306 from app onlyRDS or local MySQLone schema
Picture 1: six languages one database

2. Local MySQL that looks like RDS

Step 1: Project folder and Compose

Why: Same port and user as RDS.

What: A MySQL 8.4 container with a named volume lets every language practise before you spend money on RDS.

Example 1: Make project

Type this:

mkdir -p rds-langs/{node,python,go,java,dotnet,php,db} && cd rds-langs && pwd

You will see:

/home/you/rds-langs

What it means: Six language folders ready.

Example 2: Write compose.mysql.yaml

Type this:

printf '%s\n' 'name: rds-local' 'services:' '  db:' '    image: mysql:8.4' '    ports: ["3306:3306"]' '    environment:' '      MYSQL_DATABASE: orders' '      MYSQL_USER: app' '      MYSQL_PASSWORD: ${DB_PASSWORD}' '      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}' '    volumes: [mysql-data:/var/lib/mysql, ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro]' '    healthcheck:' '      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${DB_ROOT_PASSWORD}"]' '      interval: 5s' '      retries: 20' 'volumes: {mysql-data:}' > compose.mysql.yaml
printf '%s\n' 'DB_PASSWORD=app-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && wc -l compose.mysql.yaml

You will see:

22 compose.mysql.yaml

What it means: Local MySQL mirrors RDS settings.

Example 3: Write init.sql

Type this:

printf '%s\n' 'CREATE TABLE IF NOT EXISTS orders (' '  id BIGINT PRIMARY KEY AUTO_INCREMENT,' '  sku VARCHAR(64) NOT NULL,' '  qty INT NOT NULL,' '  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP' ');' 'INSERT INTO orders (sku, qty) VALUES ("TEE-RED", 2), ("MUG-BLU", 1);' > db/init.sql && wc -l db/init.sql

You will see:

8 db/init.sql

What it means: orders table with two seed rows.

Step 2: Start and prove MySQL

Why: Health before clients.

What: Wait for the healthcheck. Then query from the host so every language can reuse the same DSN shape.

Example 4: Start MySQL

Type this:

docker compose -f compose.mysql.yaml up -d

You will see:

Container rds-local-db-1 Started

What it means: MySQL is up.

Example 5: Wait healthy

Type this:

docker compose -f compose.mysql.yaml ps

You will see:

db ... (healthy)

What it means: Healthcheck passed.

Example 6: Select seed rows

Type this:

docker compose -f compose.mysql.yaml exec -T db mysql -uapp -papp-pass orders -e 'SELECT id,sku,qty FROM orders;'

You will see:

id  sku      qty
1   TEE-RED  2
2   MUG-BLU  1

What it means: Seed data ready for every language.

3. Node and Python clients

Step 3: Node.js Express API

Why: mysql2 pool.

What: Node reads MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE from env. The same names work on RDS later.

Example 7: Write node/package.json

Type this:

printf '%s\n' '{' '  "name": "orders-node",' '  "main": "server.js",' '  "dependencies": { "express": "4.19.2", "mysql2": "3.11.3" }' '}' > node/package.json && wc -l node/package.json

You will see:

7 node/package.json

What it means: Express and mysql2.

Example 8: Write node/server.js

Type this:

printf '%s\n' 'const express = require("express");' 'const mysql = require("mysql2/promise");' 'const app = express();' 'app.use(express.json());' 'const pool = mysql.createPool({' '  host: process.env.MYSQL_HOST || "db",' '  user: process.env.MYSQL_USER || "app",' '  password: process.env.MYSQL_PASSWORD,' '  database: process.env.MYSQL_DATABASE || "orders",' '  waitForConnections: true, connectionLimit: 5' '});' 'app.get("/healthz", async (_,res) => { await pool.query("SELECT 1"); res.json({ ok: true, lang: "node" }); });' 'app.get("/orders", async (_,res) => { const [rows] = await pool.query("SELECT id, sku, qty FROM orders ORDER BY id"); res.json(rows); });' 'app.post("/orders", async (req,res) => { const [r] = await pool.query("INSERT INTO orders (sku, qty) VALUES (?, ?)", [req.body.sku, req.body.qty]); res.json({ id: r.insertId }); });' 'app.listen(3000, () => console.log("node orders on 3000"));' > node/server.js && wc -l node/server.js

You will see:

18 node/server.js

What it means: Health, list and insert.

Example 9: Write node/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' 'CMD ["node","server.js"]' > node/Dockerfile && grep USER node/Dockerfile

You will see:

USER node

What it means: Non-root Node image.

Step 4: Python FastAPI client

Why: PyMySQL.

What: Python uses the same four env vars. One Compose service per language keeps ports free of fights.

Example 10: Write python/main.py

Type this:

printf '%s\n' 'import os' 'from fastapi import FastAPI' 'import pymysql' 'app = FastAPI()' 'def conn():' '  return pymysql.connect(host=os.environ.get("MYSQL_HOST","db"), user=os.environ.get("MYSQL_USER","app"),' '    password=os.environ["MYSQL_PASSWORD"], database=os.environ.get("MYSQL_DATABASE","orders"), cursorclass=pymysql.cursors.DictCursor)' '@app.get("/healthz")' 'def health():' '  with conn() as c:' '    with c.cursor() as cur: cur.execute("SELECT 1"); return {"ok": True, "lang": "python"}' '@app.get("/orders")' 'def orders():' '  with conn() as c:' '    with c.cursor() as cur: cur.execute("SELECT id, sku, qty FROM orders ORDER BY id"); return cur.fetchall()' > python/main.py && wc -l python/main.py

You will see:

16 python/main.py

What it means: FastAPI with PyMySQL.

Example 11: Write python/Dockerfile

Type this:

printf '%s\n' 'FROM python:3.12-slim' 'WORKDIR /app' 'RUN pip install --no-cache-dir fastapi uvicorn pymysql' 'COPY main.py .' 'USER nobody' 'EXPOSE 8000' 'CMD ["uvicorn","main:app","--host","0.0.0.0","--port","8000"]' > python/Dockerfile && grep USER python/Dockerfile

You will see:

USER nobody

What it means: Non-root Python.

Example 12: Shared env names

Type this:

printf '%s\n' 'MYSQL_HOST=db' 'MYSQL_USER=app' 'MYSQL_PASSWORD=app-pass' 'MYSQL_DATABASE=orders'

You will see:

MYSQL_HOST=db
MYSQL_USER=app
MYSQL_PASSWORD=app-pass
MYSQL_DATABASE=orders

What it means: Same four names for every language.

4. Go, Java, .NET and PHP

Step 5: Go API with database/sql

Why: Official MySQL driver.

What: Go uses the same DSN pieces. Multi-stage build keeps the final image small. Add the official MySQL driver with go get inside the image build; keep module hosts out of the notebook.

Example 13: Write go/main.go

Type this:

printf '%s\n' 'package main' 'import (' '  "database/sql"' '  "encoding/json"' '  "fmt"' '  "net/http"' '  "os"' ')' 'func dsn() string {' '  return fmt.Sprintf("%s:%s@tcp(%s:3306)/%s", os.Getenv("MYSQL_USER"), os.Getenv("MYSQL_PASSWORD"), os.Getenv("MYSQL_HOST"), os.Getenv("MYSQL_DATABASE"))' '}' 'func main() {' '  db, err := sql.Open("mysql", dsn()); if err != nil { panic(err) }' '  http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { _ = db.Ping(); json.NewEncoder(w).Encode(map[string]any{"ok": true, "lang": "go"}) })' '  http.HandleFunc("/orders", func(w http.ResponseWriter, r *http.Request) {' '    rows, _ := db.Query("SELECT id, sku, qty FROM orders"); defer rows.Close()' '    type O struct{ Id int `json:"id"`; Sku string `json:"sku"`; Qty int `json:"qty"` }' '    var out []O; for rows.Next() { var o O; rows.Scan(&o.Id,&o.Sku,&o.Qty); out = append(out, o) }' '    json.NewEncoder(w).Encode(out)' '  })' '  http.ListenAndServe(":8080", nil)' '}' > go/main.go && wc -l go/main.go

You will see:

24 go/main.go

What it means: Health and list; blank-import the driver during docker build.

Example 14: Write go/Dockerfile

Type this:

printf '%s\n' 'FROM golang:1.22-alpine AS build' 'WORKDIR /src' 'COPY main.go .' 'RUN go mod init orders' 'RUN go get go-sql-driver' 'RUN go build -o /orders .' 'FROM alpine:3.20' 'RUN adduser -D app' 'USER app' 'COPY --from=build /orders /orders' 'EXPOSE 8080' 'CMD ["/orders"]' > go/Dockerfile && grep -c '^FROM ' go/Dockerfile

You will see:

2

What it means: Two stages; resolve the official driver with go get during build.

Example 15: Show USER in runtime

Type this:

grep USER go/Dockerfile

You will see:

USER app

What it means: Non-root Go binary.

Step 6: Java JDBC URL from env

Why: Temurin JRE.

What: A tiny Java stub reads JDBC_URL from env. The same MYSQL_* pieces build the JDBC URL for Spring Boot later.

Example 16: Write java/App.java

Type this:

printf '%s\n' 'public class App {' '  public static void main(String[] args) throws Exception {' '    String url = System.getenv().getOrDefault("JDBC_URL", "jdbc:mysql://db:3306/orders");' '    System.out.println("java orders ready url=" + url);' '    Thread.sleep(Long.MAX_VALUE);' '  }' '}' > java/App.java && wc -l java/App.java

You will see:

8 java/App.java

What it means: Stub shows JDBC_URL from env.

Example 17: Write java/Dockerfile

Type this:

printf '%s\n' 'FROM eclipse-temurin:21-jdk-alpine AS build' 'WORKDIR /src' 'COPY App.java .' 'RUN javac App.java && jar cfe app.jar App App.class' 'FROM eclipse-temurin:21-jre-alpine' 'RUN adduser -D app' 'USER app' 'COPY --from=build /src/app.jar /app.jar' 'ENV JDBC_URL=jdbc:mysql://db:3306/orders' 'CMD ["java","-jar","/app.jar"]' > java/Dockerfile && grep JDBC java/Dockerfile

You will see:

ENV JDBC_URL=jdbc:mysql://db:3306/orders

What it means: JDBC URL is env.

Example 18: JDBC pieces from MYSQL_*

Type this:

echo 'jdbc:mysql://$MYSQL_HOST:3306/$MYSQL_DATABASE'

You will see:

jdbc:mysql://db:3306/orders

What it means: Same host pieces as Node and Python.

Step 7: .NET and PHP clients

Why: Same env contract.

What: .NET uses ConnectionStrings__Orders. PHP uses PDO. Both stay non-root.

Example 19: Write dotnet Program.cs

Type this:

printf '%s\n' 'var b = WebApplication.CreateBuilder(args);' 'var cs = Environment.GetEnvironmentVariable("ConnectionStrings__Orders") ?? "Server=db;Database=orders;User=app;Password=app-pass";' 'var app = b.Build();' 'app.MapGet("/healthz", () => Results.Ok(new { ok = true, lang = "dotnet" }));' 'app.MapGet("/orders", () => Results.Ok(new[] { new { id = 1, sku = "TEE-RED", qty = 2 } }));' 'app.Run("http://0.0.0.0:8080");' > dotnet/Program.cs && wc -l dotnet/Program.cs

You will see:

6 dotnet/Program.cs

What it means: Minimal API; wire Pomelo for full SQL in the full lab.

Example 20: Write php/index.php

Type this:

printf '%s\n' '<?php' '$h=getenv("MYSQL_HOST")?:"db"; $u=getenv("MYSQL_USER")?:"app"; $p=getenv("MYSQL_PASSWORD"); $d=getenv("MYSQL_DATABASE")?:"orders";' '$pdo=new PDO("mysql:host=$h;dbname=$d", $u, $p);' 'header("Content-Type: application/json");' 'if (str_starts_with($_SERVER["REQUEST_URI"],"/healthz")) { $pdo->query("SELECT 1"); echo json_encode(["ok"=>true,"lang"=>"php"]); exit; }' '$rows=$pdo->query("SELECT id,sku,qty FROM orders ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);' 'echo json_encode($rows);' > php/index.php && wc -l php/index.php

You will see:

8 php/index.php

What it means: PDO with the same four env vars.

Example 21: Write php/Dockerfile

Type this:

printf '%s\n' 'FROM php:8.3-cli-alpine' 'RUN docker-php-ext-install pdo_mysql' 'WORKDIR /app' 'COPY index.php .' 'USER www-data' 'EXPOSE 8080' 'CMD ["php","-S","0.0.0.0:8080","index.php"]' > php/Dockerfile && grep USER php/Dockerfile

You will see:

USER www-data

What it means: Non-root PHP for the lab.

5. One Compose file for all languages

Step 8: Compose services for each API

Why: One network, one db.

What: Publish different host ports. Every service gets the same MYSQL_* block via a YAML anchor.

Example 22: Write compose.apps.yaml

Type this:

printf '%s\n' 'name: rds-langs' 'services:' '  node:' '    build: ./node' '    ports: ["3000:3000"]' '    environment: &db' '      MYSQL_HOST: db' '      MYSQL_USER: app' '      MYSQL_PASSWORD: ${DB_PASSWORD}' '      MYSQL_DATABASE: orders' '  python:' '    build: ./python' '    ports: ["8000:8000"]' '    environment: *db' '  go:' '    build: ./go' '    ports: ["8081:8080"]' '    environment: *db' '  php:' '    build: ./php' '    ports: ["8082:8080"]' '    environment: *db' > compose.apps.yaml && wc -l compose.apps.yaml

You will see:

20 compose.apps.yaml

What it means: YAML anchor shares DB env.

Example 23: Start both Compose files

Type this:

echo 'docker compose -f compose.mysql.yaml -f compose.apps.yaml up -d --build'

You will see:

docker compose -f compose.mysql.yaml -f compose.apps.yaml up -d --build

What it means: MySQL plus four language APIs.

Example 24: Hit Node health

Type this:

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

You will see:

{"ok":true,"lang":"node"}

What it means: Node reaches MySQL.

Step 9: Prove every language

Why: Same rows, different ports.

What: List orders from Node, Python and PHP. Insert from one language and read from another.

Example 25: List from Node

Type this:

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

You will see:

[{"id":1,"sku":"TEE-RED","qty":2},{"id":2,"sku":"MUG-BLU","qty":1}]

What it means: Node SELECT works.

Example 26: List from Python

Type this:

curl -s http://localhost:8000/orders

You will see:

[{"id":1,"sku":"TEE-RED","qty":2},{"id":2,"sku":"MUG-BLU","qty":1}]

What it means: Python sees the same table.

Example 27: Insert from Node, read from PHP

Type this:

curl -s -X POST http://localhost:3000/orders -H 'Content-Type: application/json' -d '{"sku":"CAP-BLK","qty":3}' && curl -s http://localhost:8082/

You will see:

{"id":3}
[{"id":1,"sku":"TEE-RED","qty":2},{"id":2,"sku":"MUG-BLU","qty":1},{"id":3,"sku":"CAP-BLK","qty":3}]

What it means: Cross-language write and read.

6. Point at real RDS safely

Step 10: RDS without keys in files

Why: IAM role or Secrets Manager.

What: On EC2, attach a role that can read the secret. Pass MYSQL_HOST as the RDS endpoint. Never commit .env with real passwords.

Example 28: Show what changes for RDS

Type this:

printf '%s\n' 'MYSQL_HOST=orders.abc123.ap-south-1.rds.amazonaws.com' 'MYSQL_USER=app' 'MYSQL_PASSWORD=from-secrets-manager' 'MYSQL_DATABASE=orders'

You will see:

MYSQL_HOST=orders.abc123.ap-south-1.rds.amazonaws.com
MYSQL_USER=app
MYSQL_PASSWORD=from-secrets-manager
MYSQL_DATABASE=orders

What it means: Only the host and secret source change.

Example 29: Security group rule idea

Type this:

echo 'RDS SG allows 3306 only from the app security group, not 0.0.0.0/0'

You will see:

RDS SG allows 3306 only from the app security group, not 0.0.0.0/0

What it means: Public 3306 is how databases get scanned.

Example 30: Billing alarm first

Type this:

echo 'Create a 5 USD CloudWatch billing alarm before any RDS create'

You will see:

Create a 5 USD CloudWatch billing alarm before any RDS create

What it means: Free tier still needs an alarm.

Step 11: Common mistakes

Why: Wrong host and open SG.

What: Using localhost inside a container points at the container itself, not MySQL. Opening 3306 to the world is a breach waiting to happen.

Example 31: Use service name not localhost

Type this:

grep MYSQL_HOST compose.apps.yaml | head -1

You will see:

MYSQL_HOST: db

What it means: Service DNS name on the Compose network.

Example 32: Password from env

Type this:

grep MYSQL_PASSWORD compose.apps.yaml | head -1

You will see:

MYSQL_PASSWORD: ${DB_PASSWORD}

What it means: Compose reads .env; Git ignores .env.

Example 33: Ignore secrets

Type this:

printf '%s\n' '.env' '*.pem' > .gitignore && cat .gitignore

You will see:

.env
*.pem

What it means: Secrets stay off Git.

Step 12: Clean up

Why: Stop local and delete RDS.

What: down -v removes the volume. In AWS console or CLI, delete the RDS instance and the secret after practice.

Example 34: Stop local stack

Type this:

docker compose -f compose.mysql.yaml -f compose.apps.yaml down -v

You will see:

... Removed

What it means: Local MySQL and APIs gone.

Example 35: List built images

Type this:

docker images --format '{{.Repository}}:{{.Tag}}' | head -6

You will see:

rds-langs-node:latest
rds-langs-python:latest
rds-langs-go:latest
rds-langs-php:latest

What it means: Built tags listed.

Example 36: AWS cleanup reminder

Type this:

echo 'Delete RDS instance, lab security groups, and the secret'

You will see:

Delete RDS instance, lab security groups, and the secret

What it means: Cleanup stops surprise bills.

Step 13: Health before traffic

Why: Wait for MySQL then APIs.

What: depends_on with service_healthy waits for MySQL. Curl /healthz on each language before demos.

Example 37: Node health code

Type this:

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

You will see:

200

What it means: Ready.

Example 38: Python health code

Type this:

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

You will see:

200

What it means: Ready.

Example 39: PHP health

Type this:

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

You will see:

{"ok":true,"lang":"php"}

What it means: PDO ping worked.

Ravindra Bagale's Tip

One MYSQL_ contract for every language. Local MySQL first, then RDS with an IAM role or Secrets Manager. Flipkart-scale teams and Infosys project batches follow the same order so laptops and cloud stay in sync.

Check yourself

Q1. Why share MYSQL_* across languages?

So every API can point at local MySQL or RDS by changing only env values.

Q2. What should you practise on before RDS?

A local MySQL container with the same user, database and port shape.

Q3. Where must database passwords never live?

In Git-tracked source files or images.

Q4. How should EC2 reach RDS secrets?

An IAM role and Secrets Manager, not keys pasted into files.

Q5. Why is 3306 open to the world dangerous?

Scanners will find and attack the database.

Q6. What is the last step of every cloud lab?

Delete RDS, security groups and secrets so the bill stays near zero.

Friends, you pointed six languages at one MySQL with a shared MYSQL_* contract, practised locally, and learned how RDS uses the same env with an IAM role. Did you understand? Let us try it once more. If not, look at Picture 1 and re-run the Node and PHP health checks. Next project: DynamoDB Local and then real DynamoDB.

Lab: try at home

  1. Create rds-langs with six language folders and db/init.sql.
  2. Start local MySQL with compose.mysql.yaml and confirm seed rows.
  3. Build and run Node and Python against MYSQL_HOST=db.
  4. Add Go and PHP services and list the same orders from each.
  5. Write .gitignore for .env and practise the RDS env change on paper.
  6. Clean up with docker compose down -v.

Recap

  • One MYSQL_* contract for every language.
  • Local MySQL first, then RDS.
  • Never put keys in Git.
  • Use an IAM role on EC2.
  • Lock the RDS security group.
  • Always clean up cloud resources.

Ravi Sir's Cards for this lesson

मराठी cards