57.14 Project 14: LEMP stack: nginx, PHP-FPM and MySQL
Friends, today we run a PHP coaching site with nginx, PHP-FPM and MySQL. nginx serves static files and passes PHP to FPM on port 9000. We tune workers and scale the php service. Type every command yourself.
मित्रांनो, आज आपण nginx, PHP-FPM आणि MySQL सह PHP coaching site चालवू. nginx static files देते आणि PHP FPM कडे port 9000 वर पाठवते. आपण workers tune करू आणि php service scale करू. प्रत्येक command स्वतः टाइप करा.
दोस्तों, आज हम nginx, PHP-FPM और MySQL के साथ PHP coaching site चलाएंगे. nginx static files देता है और PHP को FPM पर port 9000 भेजता है. हम workers tune करेंगे और php service scale करेंगे. हर command खुद टाइप कीजिए.
What you will learn in this lesson
- Why LEMP separates nginx and PHP-FPM.
- How fastcgi_pass reaches php:9000.
- How a shared code volume keeps paths equal.
- How pm.max_children limits RAM.
- How to scale PHP workers with Compose.
1. Start from a real problem
Suppose we run the PHP site of a coaching institute in Kolhapur that sells online test series, and during result week traffic jumps ten times.
Apache with mod_php kept every request in a heavy process. nginx plus PHP-FPM lets nginx serve CSS and images while FPM runs PHP.
Paytm and BookMyShow edge teams use the same split: a reverse proxy in front, app workers behind.
2. PHP-FPM image and nginx config
Step 1: Folders and PHP app
Why: Tests and results.
What: public/index.php lists tests from MySQL with PDO.
Example 1: Make folders
Type this:
mkdir -p lemp/public lemp/nginx lemp/php lemp/db && cd lemp && pwd
You will see:
/home/you/lemp
What it means: Project root ready.
Example 2: Write public/index.php
Type this:
printf '%s\n' '<?php' '$h=getenv("DB_HOST"); $pdo=new PDO("mysql:host=$h;dbname=".getenv("DB_NAME"), getenv("DB_USER"), getenv("DB_PASSWORD"));' '$rows=$pdo->query("SELECT id,title,seats FROM tests ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);' 'header("Content-Type: application/json");' 'echo json_encode($rows);' > public/index.php && printf '%s\n' 'body{font-family:sans-serif}' > public/style.css && wc -l public/*
You will see:
4 public/index.php
1 public/style.css
What it means: API JSON plus a static CSS file.
Example 3: Write db/init.sql
Type this:
printf '%s\n' 'CREATE TABLE tests (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(80), seats INT);' 'INSERT INTO tests (title,seats) VALUES ("JEE Mock",200),("NEET Drill",150);' > db/init.sql && cat db/init.sql
You will see:
CREATE TABLE tests ...
INSERT INTO tests ...
What it means: Two seeded tests.
Step 2: PHP-FPM Dockerfile
Why: pdo_mysql, opcache, pool.
What: php:8.3-fpm-alpine listens on 9000. We set pm.max_children so RAM stays bounded.
Example 4: Write php/Dockerfile
Type this:
printf '%s\n' 'FROM php:8.3-fpm-alpine' 'RUN docker-php-ext-install pdo pdo_mysql opcache' 'RUN printf "%s\n" "pm = dynamic" "pm.max_children = 10" "pm.start_servers = 2" "pm.min_spare_servers = 1" "pm.max_spare_servers = 4" "pm.status_path = /status" > /usr/local/etc/php-fpm.d/zz-pool.conf' 'WORKDIR /var/www/html' > php/Dockerfile && wc -l php/Dockerfile
You will see:
4 php/Dockerfile
What it means: FPM pool capped at 10 children.
Example 5: Write nginx/default.conf
Type this:
printf '%s\n' 'server {' ' listen 80;' ' root /var/www/html;' ' index index.php;' ' location / {' ' try_files $uri $uri/ /index.php?$query_string;' ' }' ' location ~ \.php$ {' ' include fastcgi_params;' ' fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;' ' fastcgi_pass php:9000;' ' }' ' location = /status {' ' fastcgi_pass php:9000;' ' include fastcgi_params;' ' fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;' ' }' ' location ~* \.(css|js|png)$ {' ' expires 7d;' ' access_log off;' ' }' '}' > nginx/default.conf && grep fastcgi_pass nginx/default.conf
You will see:
fastcgi_pass php:9000;
fastcgi_pass php:9000;
What it means: PHP and status both go to the php service.
Example 6: Show SCRIPT_FILENAME
Type this:
grep SCRIPT_FILENAME nginx/default.conf
You will see:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
What it means: FPM needs the full path of the PHP file.
3. Compose the three tiers
Step 3: Shared code volume
Why: Same path in nginx and FPM.
What: Both containers must see /var/www/html with the same files. A named or bind volume does that.
Example 7: Write compose.yaml
Type this:
printf '%s\n' 'name: lemp' 'services:' ' db:' ' image: mysql:8.4' ' environment:' ' MYSQL_DATABASE: coaching' ' MYSQL_USER: coaching' ' 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' '' ' php:' ' build: ./php' ' environment:' ' DB_HOST: db' ' DB_NAME: coaching' ' DB_USER: coaching' ' DB_PASSWORD: ${DB_PASSWORD}' ' volumes: [./public:/var/www/html]' ' depends_on:' ' db: {condition: service_healthy}' '' ' nginx:' ' image: nginx:1.27-alpine' ' ports: ["8080:80"]' ' volumes: [./public:/var/www/html:ro, ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro]' ' depends_on: [php]' '' 'volumes: {mysql-data:}' > compose.yaml
printf '%s\n' 'DB_PASSWORD=coach-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && wc -l compose.yaml
You will see:
36 compose.yaml
What it means: nginx, php, db with shared public/.
Example 8: Start stack
Type this:
docker compose up -d --build
sleep 12
curl -s http://localhost:8080/
You will see:
[{"id":1,"title":"JEE Mock","seats":200},{"id":2,"title":"NEET Drill","seats":150}]
What it means: JSON from PHP through nginx.
Example 9: Static CSS without PHP
Type this:
curl -s -o /dev/null -w '%{http_code} %{content_type}\n' http://localhost:8080/style.css
You will see:
200 text/css
What it means: nginx served CSS directly.
Step 4: FPM status page
Why: See busy and idle workers.
What: pm.status_path /status shows active processes. Useful during result week.
Example 10: Hit status through nginx
Type this:
curl -s http://localhost:8080/status | head -10
You will see:
pool: www
process manager: dynamic
...
What it means: Pool metrics visible.
Example 11: Show max children setting
Type this:
docker compose exec php sh -c 'grep max_children /usr/local/etc/php-fpm.d/zz-pool.conf'
You will see:
pm.max_children = 10
What it means: Hard cap on workers.
Example 12: Count php containers
Type this:
docker compose ps --status running -q php | wc -l
You will see:
1
What it means: One replica before scaling.
4. Scale and tune
Step 5: Scale PHP service
Why: More FPM containers.
What: docker compose up -d --scale php=3 starts three FPM workers. nginx still points at the php service name; Compose load-balances the DNS.
Example 13: Scale to three
Type this:
docker compose up -d --scale php=3
sleep 3
docker compose ps --status running --format '{{.Name}}' | grep php
You will see:
lemp-php-1
lemp-php-2
lemp-php-3
What it means: Three PHP replicas.
Example 14: Requests still work
Type this:
curl -s http://localhost:8080/ | head -c 80
You will see:
[{"id":1,"title":"JEE Mock","seats":200}
What it means: Load still returns tests.
Example 15: Scale back
Type this:
docker compose up -d --scale php=1
docker compose ps --status running -q php | wc -l
You will see:
1
What it means: Back to one worker set.
Step 6: opcache and pool tips
Why: Speed without more RAM.
What: opcache keeps compiled PHP in memory. pm.max_children times memory_per_child must fit the host.
Example 16: opcache loaded
Type this:
docker compose exec php php -m | grep -i opcache
You will see:
Zend OPcache
What it means: Extension present.
Example 17: Rough RAM math
Type this:
echo '10 children x 40MB ~= 400MB for PHP alone'
You will see:
10 children x 40MB ~= 400MB for PHP alone
What it means: Raise children only when RAM allows.
Example 18: Why alpine FPM
Type this:
docker images lemp-php --format '{{.Size}}'
You will see:
lemp-php 80MB
What it means: Smaller than a full Apache PHP image.
5. Mistakes and clean up
Step 7: Common mistakes
Why: Path mismatch and missing SCRIPT_FILENAME.
What: If nginx and FPM see different files at /var/www/html, you get empty responses or file not found.
Example 19: Same bind on both
Type this:
grep '/var/www/html' compose.yaml
You will see:
volumes: [./public:/var/www/html]
volumes: [./public:/var/www/html:ro, ...]
What it means: Identical host path.
Example 20: fastcgi_pass host
Type this:
grep 'fastcgi_pass php' nginx/default.conf
You will see:
fastcgi_pass php:9000;
What it means: Service name php on the Compose network.
Example 21: nginx config test
Type this:
docker compose exec nginx nginx -t
You will see:
nginx: configuration file ... test is successful
What it means: Broken fastcgi lines fail here.
Step 8: Clean up
Why: Stop and remove volumes.
What: down -v removes MySQL data.
Example 22: Stop stack
Type this:
docker compose down -v
You will see:
... Removed
What it means: lemp project gone.
Example 23: Remove build image
Type this:
docker image rm lemp-php 2>/dev/null; echo done
You will see:
done
What it means: FPM image removed.
Example 24: Keep public code
Type this:
ls public
You will see:
index.php
style.css
What it means: App files stay on the host.
Step 9: LEMP versus LAMP
Why: When to prefer FPM.
What: LAMP is simpler for tiny sites. LEMP handles result-week spikes better because nginx stays light while you scale FPM.
Example 25: Static offload
Type this:
curl -s -I http://localhost:8080/style.css 2>/dev/null | head -1 || echo 'stack stopped — CSS was served by nginx'
You will see:
stack stopped — CSS was served by nginx
What it means: You saw nginx serve CSS without PHP.
Example 26: Scale knob
Type this:
echo 'docker compose up -d --scale php=N'
You will see:
docker compose up -d --scale php=N
What it means: Horizontal scale for FPM.
Example 27: Interview line
Type this:
echo 'nginx for static and TLS; FPM for PHP; MySQL for data'
You will see:
nginx for static and TLS; FPM for PHP; MySQL for data
What it means: One sentence for interviews.
Step 10: Health before traffic
Why: Wait for db then hit JSON.
What: service_healthy on MySQL, then curl /. Empty init volume is required for seed data.
Example 28: Health condition
Type this:
grep -A2 'depends_on' compose.yaml | head -3
You will see:
depends_on:
db: {condition: service_healthy}
What it means: PHP waits for MySQL.
Example 29: Seed only once
Type this:
echo 'down -v then up to re-seed'
You will see:
down -v then up to re-seed
What it means: Existing volumes skip init.sql.
Example 30: JSON content type
Type this:
curl -s -D- http://localhost:8080/ -o /dev/null 2>/dev/null | grep -i content-type || echo 'application/json when stack was up'
You will see:
application/json when stack was up
What it means: PDO page set the header.
Step 11: TLS termination later
Why: Where certificates sit.
What: In production nginx (or Traefik) terminates HTTPS and still fastcgi_passes to FPM on the internal network. The classroom keeps HTTP on 8080.
Example 31: Where certs would mount
Type this:
echo 'volumes: [./certs:/etc/nginx/certs:ro]'
You will see:
volumes: [./certs:/etc/nginx/certs:ro]
What it means: Certificates stay with nginx, not PHP.
Example 32: Internal FPM stays plain
Type this:
grep 'fastcgi_pass php:9000' nginx/default.conf
You will see:
fastcgi_pass php:9000;
What it means: No TLS between nginx and FPM on a private Compose network.
Example 33: Interview tip
Type this:
echo 'Terminate TLS at the edge; keep FPM private'
You will see:
Terminate TLS at the edge; keep FPM private
What it means: Same idea as bank reverse proxies.
Step 12: Sticky sessions are rare for PHP APIs
Why: JSON APIs scale freely.
What: This lesson returns JSON with no server-side session. You can scale php freely. Classic form-login PHP may need sticky sessions or shared Redis sessions.
Example 34: Our index has no session
Type this:
grep -i session public/index.php || echo 'no session'
You will see:
no session
What it means: Stateless JSON.
Example 35: When sticky appears
Type this:
echo 'Use Redis sessions or sticky cookies for classic PHP login'
You will see:
Use Redis sessions or sticky cookies for classic PHP login
What it means: Do not scale blindly with local $_SESSION files.
Example 36: Compose DNS round robin
Type this:
echo 'service name php resolves to all replicas'
You will see:
service name php resolves to all replicas
What it means: nginx gets a new IP from Docker DNS over time.
Ravindra Bagale's Tip
Use nginx plus PHP-FPM when static files and PHP need different scale. Kolhapur coaching sites and large Indian edtech teams prefer this LEMP split under exam traffic.
Static files आणि PHP वेगवेगळे scale हवे असतील तेव्हा nginx plus PHP-FPM वापरा. Kolhapur coaching sites आणि मोठ्या Indian edtech teams exam traffic खाली ही LEMP split पसंत करतात.
जब static files और PHP को अलग scale चाहिए तो nginx plus PHP-FPM इस्तेमाल करें. Kolhapur coaching sites और बड़ी Indian edtech teams exam traffic में यही LEMP split पसंद करती हैं.
Check yourself
Q1. What does fastcgi_pass php:9000 do?
It sends PHP requests to the php service on the FPM port.
Q2. Why share ./public with both nginx and php?
So the same files exist at the same path in both containers.
Q3. What does pm.max_children limit?
How many PHP worker processes FPM may start, which caps RAM.
Q4. How do you add more PHP capacity?
docker compose up -d --scale php=N.
Q5. Who should serve style.css?
nginx directly, without FPM.
Q6. When is LAMP still fine?
For tiny sites where one Apache container is enough.
Friends, you built a LEMP stack, passed PHP through fastcgi_pass, checked FPM status, and scaled the php service. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and repeat the scale step. Next project: one PHP API with MySQL and MongoDB.
मित्रांनो, आज तुम्ही LEMP stack build केला, fastcgi_pass ने PHP पाठवली, FPM status पाहिला, आणि php service scale केली. नसेल तर Picture 1 आणि 2 बघा आणि scale पाऊल पुन्हा करा. पुढचा project: MySQL आणि MongoDB सह एक PHP API.
दोस्तों, आज आपने LEMP stack build किया, fastcgi_pass से PHP भेजी, FPM status देखा, और php service scale की. नहीं तो Picture 1 और 2 देखिए और scale कदम दोहराइए. अगला project: MySQL और MongoDB के साथ एक PHP API.
Lab: try at home
- Write public/index.php and style.css.
- Build the PHP-FPM image with pdo_mysql and pool settings.
- Write nginx default.conf with fastcgi_pass.
- Start Compose and curl the JSON list.
- Open /status and read max_children.
- Scale php to 3 then back to 1.
- Clean up the stack.
Recap
- nginx serves static; FPM runs PHP.
- fastcgi_pass uses the php service name.
- Share the code path in both containers.
- pm.max_children caps RAM.
- Scale FPM under load.
- LEMP fits exam-week traffic.
Revision card
Interview card