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.15 Project 15: PHP with MySQL and with MongoDB (one API, two databases)

Friends, today one PHP API image talks to MySQL or MongoDB. We install pdo_mysql and the mongodb extension, write one ProductStore style API, and run two Compose files. Type every command yourself.

What you will learn in this lesson

  1. Why one API may need two database drivers.
  2. How pecl install mongodb adds the extension.
  3. How DB_KIND switches MySQL and Mongo stores.
  4. How JSON columns compare to documents.
  5. How to back up both databases.

1. Start from a real problem

Suppose we build the product catalogue API for a Pune electronics shop that sells on Amazon and Flipkart, and the team is not sure which database to pick.

MySQL fits structured SKUs. MongoDB fits flexible specs. The shop wants one codebase while they decide.

With Docker we ship one PHP image that has both drivers and choose the store with DB_KIND.

PHP API imagepdo_mysql + mongodb extDB_KIND=mysqlJSON column for specsDB_KIND=mongodocument per productSame routes/healthz /products
Picture 1: one image two stores

2. Image with both drivers

Step 1: Folders and Dockerfile

Why: pecl mongodb plus pdo.

What: We pin mongodb-1.20.0 with pecl. Composer is optional here; the classroom uses the extension API directly to avoid extra hosts.

Example 1: Make folders

Type this:

mkdir -p php-db/public php-db/db && cd php-db && pwd

You will see:

/home/you/php-db

What it means: Project root ready.

Example 2: Write Dockerfile

Type this:

printf '%s\n' 'FROM php:8.3-cli-alpine' 'RUN apk add --no-cache $PHPIZE_DEPS openssl-dev' 'RUN docker-php-ext-install pdo pdo_mysql' 'RUN pecl install mongodb-1.20.0 && docker-php-ext-enable mongodb' 'WORKDIR /app' 'COPY public/ /app/public/' 'EXPOSE 8080' 'CMD ["php", "-S", "0.0.0.0:8080", "-t", "public", "public/index.php"]' > Dockerfile && wc -l Dockerfile

You will see:

8 Dockerfile

What it means: CLI image with built-in server for the API demo.

Example 3: Build php-db:1.0

Type this:

docker build -t php-db:1.0 .

You will see:

... FINISHED

What it means: Image with both drivers.

Step 2: Prove extensions

Why: php -m inside the image.

What: Both pdo_mysql and mongodb must show up before we write routes.

Example 4: List drivers

Type this:

docker run --rm php-db:1.0 php -m | grep -E 'pdo_mysql|^mongodb$'

You will see:

pdo_mysql
mongodb

What it means: Both extensions loaded.

Example 5: PHP version

Type this:

docker run --rm php-db:1.0 php -r 'echo PHP_VERSION, PHP_EOL;'

You will see:

8.3.x

What it means: Matches the base tag.

Example 6: No Composer in final CMD

Type this:

grep '^CMD' Dockerfile

You will see:

CMD ["php", "-S", "0.0.0.0:8080", "-t", "public", "public/index.php"]

What it means: Built-in server keeps the demo small.

3. One API two stores

Step 3: index.php router

Why: DB_KIND chooses the store.

What: Routes: GET /healthz, GET /products, POST /products. MySQL uses a JSON column for specs; Mongo stores a document.

Example 7: Write public/index.php

Type this:

printf '%s\n' '<?php' 'declare(strict_types=1);' '$kind=getenv("DB_KIND")?:"mysql";' '$uri=parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);' '$method=$_SERVER["REQUEST_METHOD"];' 'header("Content-Type: application/json");' 'function mysql(){ $p=new PDO("mysql:host=".getenv("DB_HOST").";dbname=".getenv("DB_NAME"), getenv("DB_USER"), getenv("DB_PASSWORD")); $p->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); return $p; }' 'function mongo(){ $m=new MongoDB\\Driver\\Manager(getenv("MONGO_URL")); return $m; }' 'if($uri==="/healthz"){ echo json_encode(["ok"=>true,"engine"=>$kind]); exit; }' 'if($uri==="/products" && $method==="GET"){' '  if($kind==="mongo"){ $q=new MongoDB\\Driver\\Query([]); $rows=mongo()->executeQuery("shop.products",$q); $out=[]; foreach($rows as $r){ $out[]=$r; } echo json_encode($out); exit; }' '  $rows=mysql()->query("SELECT id,name,specs FROM products")->fetchAll(PDO::FETCH_ASSOC); echo json_encode($rows); exit;' '}' 'if($uri==="/products" && $method==="POST"){' '  $b=json_decode(file_get_contents("php://input"), true);' '  if($kind==="mongo"){ $bulk=new MongoDB\\Driver\\BulkWrite; $bulk->insert(["name"=>$b["name"],"specs"=>$b["specs"]??[]]); mongo()->executeBulkWrite("shop.products",$bulk); echo json_encode(["saved"=>true]); exit; }' '  $st=mysql()->prepare("INSERT INTO products(name,specs) VALUES(?,CAST(? AS JSON))"); $st->execute([$b["name"], json_encode($b["specs"]??[])]); echo json_encode(["saved"=>true]); exit;' '}' 'http_response_code(404); echo json_encode(["error"=>"not found"]);' > public/index.php && wc -l public/index.php

You will see:

22 public/index.php

What it means: Health, list and create for both engines.

Example 8: Show DB_KIND default

Type this:

grep DB_KIND public/index.php | head -1

You will see:

$kind=getenv("DB_KIND")?:"mysql";

What it means: Default engine is mysql.

Example 9: Rebuild with code

Type this:

docker build -t php-db:1.0 .

You will see:

... FINISHED

What it means: index.php copied into the image.

Step 4: MySQL Compose

Why: JSON column for specs.

What: init.sql creates products with a JSON specs column.

Example 10: Write db/init.sql and compose.mysql.yaml

Type this:

printf '%s\n' 'CREATE TABLE products (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(120) NOT NULL, specs JSON NULL);' > db/init.sql
printf '%s\n' 'name: php-mysql' 'services:' '  db:' '    image: mysql:8.4' '    environment:' '      MYSQL_DATABASE: shop' '      MYSQL_USER: shop' '      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' '' '  api:' '    image: php-db:1.0' '    ports: ["8080:8080"]' '    environment:' '      DB_KIND: mysql' '      DB_HOST: db' '      DB_NAME: shop' '      DB_USER: shop' '      DB_PASSWORD: ${DB_PASSWORD}' '    depends_on:' '      db: {condition: service_healthy}' '' 'volumes: {mysql-data:}' > compose.mysql.yaml
printf '%s\n' 'DB_PASSWORD=shop-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && docker compose -f compose.mysql.yaml up -d

You will see:

... Started

What it means: MySQL stack on 8080.

Example 11: Health and create

Type this:

curl -s http://localhost:8080/healthz
curl -s -X POST http://localhost:8080/products -H 'Content-Type: application/json' -d '{"name":"Router","specs":{"band":"ax","ports":4}}'

You will see:

{"ok":true,"engine":"mysql"}
{"saved":true}

What it means: MySQL engine healthy; product saved.

Example 12: List products

Type this:

curl -s http://localhost:8080/products

You will see:

[{"id":1,"name":"Router","specs":{"band":"ax","ports":4}}]

What it means: JSON column round trip works.

4. Mongo stack and backups

POST /productsbody with name+specsDB_KIND=mysqlJSON columnDB_KIND=mongoBSON document
Picture 2: same routes different engine

Step 5: Mongo Compose

Why: Same image, DB_KIND=mongo.

What: Host port 8081 avoids clashing with MySQL.

Example 13: Write compose.mongo.yaml

Type this:

printf '%s\n' 'name: php-mongo' 'services:' '  db:' '    image: mongo:7' '    volumes: [mongo-data:/data/db]' '    healthcheck:' '      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand(\"ping\").ok"]' '      interval: 5s' '      retries: 20' '' '  api:' '    image: php-db:1.0' '    ports: ["8081:8080"]' '    environment:' '      DB_KIND: mongo' '      MONGO_URL: mongodb://db:27017' '    depends_on:' '      db: {condition: service_healthy}' '' 'volumes: {mongo-data:}' > compose.mongo.yaml && docker compose -f compose.mongo.yaml up -d

You will see:

... Started

What it means: Mongo stack on 8081.

Example 14: Health and create on 8081

Type this:

curl -s http://localhost:8081/healthz
curl -s -X POST http://localhost:8081/products -H 'Content-Type: application/json' -d '{"name":"Router","specs":{"band":"ax","ports":4}}'

You will see:

{"ok":true,"engine":"mongo"}
{"saved":true}

What it means: Same API, mongo engine.

Example 15: List on 8081

Type this:

curl -s http://localhost:8081/products | head -c 120

You will see:

[{name:Router, specs:{band:ax}}]

What it means: Document stored.

Step 6: Back up both

Why: mysqldump and mongodump.

What: Keep both dumps when the shop is still deciding.

Example 16: MySQL dump

Type this:

mkdir -p backups && docker compose -f compose.mysql.yaml exec -T -e MYSQL_PWD=shop-pass db mysqldump -ushop shop > backups/shop.sql && wc -l backups/shop.sql

You will see:

30 backups/shop.sql

What it means: SQL backup saved.

Example 17: Mongo dump

Type this:

docker compose -f compose.mongo.yaml exec -T db mongodump --archive > backups/shop.archive && ls -lh backups/shop.archive

You will see:

-rw-r--r-- ... backups/shop.archive

What it means: BSON archive saved.

Example 18: Same image id

Type this:

docker inspect -f '{{.Image}}' $(docker compose -f compose.mysql.yaml ps -q api) $(docker compose -f compose.mongo.yaml ps -q api) | sort -u | wc -l

You will see:

1

What it means: One artifact for both stacks.

5. Mistakes and clean up

Step 7: Common mistakes

Why: Missing pecl build deps.

What: pecl needs $PHPIZE_DEPS and openssl-dev on Alpine. Skipping them fails the mongodb build.

Example 19: Show pecl line

Type this:

grep pecl Dockerfile

You will see:

RUN pecl install mongodb-1.20.0 && docker-php-ext-enable mongodb

What it means: Pinned driver version.

Example 20: Show build deps

Type this:

grep PHPIZE Dockerfile

You will see:

RUN apk add --no-cache $PHPIZE_DEPS openssl-dev

What it means: Headers required to compile.

Example 21: Engine must be set

Type this:

grep DB_KIND compose.mysql.yaml

You will see:

DB_KIND: mysql

What it means: Without it the wrong store may load.

Step 8: JSON column versus document

Why: Flexibility trade-off.

What: MySQL JSON keeps SQL joins for orders. Mongo documents change shape without ALTER TABLE. Amazon DocumentDB is Mongo compatible for many PHP apps.

Example 22: MySQL specs type

Type this:

grep JSON db/init.sql

You will see:

CREATE TABLE products (..., specs JSON NULL);

What it means: Flexible fields inside SQL.

Example 23: Mongo needs no migration

Type this:

echo 'insert documents with new keys anytime'

You will see:

insert documents with new keys anytime

What it means: No ALTER TABLE for new spec keys.

Example 24: Pick later

Type this:

echo 'keep DB_KIND until the shop chooses'

You will see:

keep DB_KIND until the shop chooses

What it means: One codebase while you decide.

Step 9: Clean up

Why: Stop both stacks.

What: down -v each file. Keep backups/.

Example 25: Stop MySQL

Type this:

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

You will see:

... Removed

What it means: php-mysql gone.

Example 26: Stop Mongo

Type this:

docker compose -f compose.mongo.yaml down -v

You will see:

... Removed

What it means: php-mongo gone.

Example 27: Remove image

Type this:

docker image rm php-db:1.0

You will see:

Untagged: php-db:1.0

What it means: Disk space returned.

Step 10: Built-in server versus FPM

Why: When to graduate.

What: php -S is fine for an API demo. For real traffic use PHP-FPM with nginx as in Project 14.

Example 28: CMD uses built-in server

Type this:

grep 'php -S' Dockerfile

You will see:

CMD ["php", "-S", "0.0.0.0:8080", "-t", "public", "public/index.php"]

What it means: Router file is public/index.php.

Example 29: Next step

Type this:

echo 'Move the same index.php behind nginx + FPM for production'

You will see:

Move the same index.php behind nginx + FPM for production

What it means: Drivers stay the same.

Example 30: Health first

Type this:

curl -s http://localhost:8080/healthz 2>/dev/null || echo 'stack stopped'

You will see:

stack stopped

What it means: Always health-check before load tests.

Step 11: Compare query shapes

Why: SQL filter versus document filter.

What: MySQL can filter JSON with JSON_EXTRACT. Mongo filters on nested keys. The shop can try both against the same product names.

Example 31: MySQL JSON extract idea

Type this:

echo "SELECT name FROM products WHERE JSON_EXTRACT(specs,'$.band')='ax';"

You will see:

SELECT name FROM products WHERE JSON_EXTRACT(specs,'$.band')='ax';

What it means: SQL over JSON fields.

Example 32: Mongo filter idea

Type this:

echo 'db.products.find({ "specs.band": "ax" })'

You will see:

db.products.find({ "specs.band": "ax" })

What it means: Document query on nested key.

Example 33: Same business question

Type this:

echo 'Which routers are Wi-Fi ax?'

You will see:

Which routers are Wi-Fi ax?

What it means: Two syntaxes, one question.

Step 12: Pin extension versions

Why: Reproducible builds.

What: pecl install mongodb without a version can break next week. Pin mongodb-1.20.0 like the Dockerfile.

Example 34: Pinned pecl

Type this:

grep 'pecl install' Dockerfile

You will see:

RUN pecl install mongodb-1.20.0 && docker-php-ext-enable mongodb

What it means: Exact version.

Example 35: Rebuild is deterministic

Type this:

echo 'same Dockerfile => same extension'

You will see:

same Dockerfile => same extension

What it means: CI and laptops match.

Example 36: Upgrade deliberately

Type this:

echo 'bump the pecl version in a PR, rebuild, retest both stacks'

You will see:

bump the pecl version in a PR, rebuild, retest both stacks

What it means: Never float driver versions in production.

Ravindra Bagale's Tip

Ship both drivers when the database choice is still open. Pune shops selling on Amazon and Flipkart often keep MySQL for orders and try Mongo for catalogue specs.

Check yourself

Q1. Why install both drivers in one image?

So one codebase can talk to MySQL or MongoDB while the team decides.

Q2. How do you add the MongoDB PHP extension?

pecl install a pinned mongodb version and docker-php-ext-enable.

Q3. What switches the store at runtime?

The DB_KIND environment variable.

Q4. How does MySQL store flexible specs here?

A JSON column on the products table.

Q5. How do you back up Mongo in this lesson?

mongodump --archive from the db container.

Q6. When should you leave php -S?

When real traffic arrives; move to nginx plus PHP-FPM.

Friends, you built one PHP image with two drivers, ran MySQL and Mongo stacks, compared JSON columns to documents, and took both backups. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and compare /healthz on 8080 and 8081. Next project: 3-tier React, Node and PostgreSQL.

Lab: try at home

  1. Build php-db:1.0 with pdo_mysql and pecl mongodb.
  2. Write the router in public/index.php.
  3. Start MySQL Compose and create a product.
  4. Start Mongo Compose on 8081 and create the same product.
  5. Dump both databases into backups/.
  6. Confirm both APIs share one image id.
  7. Clean up both stacks.

Recap

  • One PHP image can carry two drivers.
  • DB_KIND switches MySQL and Mongo.
  • JSON columns add flexibility inside SQL.
  • Documents skip ALTER TABLE.
  • Back up both while you decide.
  • Graduate to FPM under real traffic.

Ravi Sir's Cards for this lesson

मराठी cards