EthicsComputerCourses
Join training +91 90532 10052

LEMP with Docker Compose

LEMP Stack · Lesson 18 of 20 Project 15 min read Updated

By the end of this project the Kochi Bakery menu will run in three containers: Nginx, PHP-FPM and MySQL, started with one docker compose up. You will write the PHP image, wire Nginx to PHP-FPM across a container network, give MySQL its passwords as secret files, load the cake table on first start, lock the database user down to four privileges, and finally publish the stack as a staging site behind the server's own Nginx with HTTPS.

What you should know first: the whole LEMP flow from Connecting Nginx to PHP-FPM and MySQL Setup, Users & Security, and the Docker basics from Docker Compose Basics, Compose: depends_on, Healthchecks & Profiles and Environment Variables & Secrets. Image versions were checked on Docker Hub on 16 November 2026: nginx:1.30 (1.30.6), php:8.5-fpm (8.5.12, Debian trixie) and mysql:8.4 (8.4.13). Facts about the images come from their official documentation and Dockerfiles. Docker is not installed on the machine where this lesson was tested, so compose.yaml was checked against the Compose Specification's JSON schema, the Nginx config passed nginx -t with Nginx 1.28.3, and the PHP pages ran behind that Nginx with a SQLite stand-in for MySQL. Docker's own outputs below are described from its documentation.

The plan

On the server you built in this course, Nginx, PHP-FPM and MySQL are three services on one machine, talking through a Unix socket and 127.0.0.1. In Compose they become three containers, each from its own image, joined by a private network.

Think of a food court in a Kochi mall. Each counter is a separate stall with its own staff, but they share one hall and one entrance. Customers only reach the counters through the entrance (the published port). The stalls pass orders to each other by calling out names ("php", "db"), because Compose gives every service a DNS name on its network.

PartOn the LEMP serverIn this project
Web serverNginx package, kochibakery.confweb service, image nginx:1.30, default.conf mounted read-only
PHPphp8.5-fpm pool on /run/php/kochibakery.sockphp service, built from php:8.5-fpm, listening on port 9000 inside the network
Databasemysql-server on 127.0.0.1:3306db service, image mysql:8.4, data in the volume db-data
Secretsconfig.php with mode 640Files in secrets/, mounted at /run/secrets/

Why use containers at all, when the server works? A developer's laptop gets exactly the server's versions with one command, a staging copy can run beside production, and the whole setup lives in Git as plain files.

Step 1: the project folder

Create this layout on your laptop or server, in a folder called kochibakery-docker:

Text
kochibakery-docker/
├── compose.yaml
├── .gitignore
├── app/
│   ├── public/
│   │   ├── health.php
│   │   └── index.php
│   └── src/
│       └── db.php
├── db/
│   └── init.sql
├── docker/
│   ├── nginx/
│   │   └── default.conf
│   └── php/
│       ├── Dockerfile
│       └── app.ini
└── secrets/
    ├── db_password.txt
    └── db_root_password.txt

As on the server, only app/public is visible on the web. Add one line to .gitignore so passwords never reach Git:

Text
/secrets/

Step 2: the secrets

Generate two random passwords. openssl rand prints 24 random bytes as text:

Terminal
mkdir -p secrets
openssl rand -base64 24 > secrets/db_password.txt
openssl rand -base64 24 > secrets/db_root_password.txt
chmod 700 secrets
chmod 644 secrets/*.txt

The permissions look backwards but are deliberate. Compose delivers a file secret by bind-mounting the file into the container, and its documentation says the uid, gid and mode options are ignored for file secrets. The file keeps its host permissions, so the mysql user inside the db container and www-data inside the php container must be able to read it. The 700 folder still stops other users on your machine from reaching the files.

Secret files are safer than plain environment variables: they do not show up in docker inspect or in the environment of every process.

Step 3: the PHP image

The official php image has helper scripts for extensions. docker/php/Dockerfile:

Dockerfile
FROM php:8.5-fpm

RUN docker-php-ext-install pdo_mysql \
    && mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"

COPY app.ini "$PHP_INI_DIR/conf.d/zz-app.ini"
  • docker-php-ext-install pdo_mysql compiles PDO MySQL, the only extension the menu needs beyond the built-in ones.
  • The image ships php.ini-development and php.ini-production but uses neither until you choose. Production turns display_errors off.
  • Files in $PHP_INI_DIR/conf.d/ (/usr/local/etc/php/conf.d) are read after php.ini; the zz- prefix makes ours load last.

docker/php/app.ini holds the few settings that differ from upstream PHP:

Text
expose_php = Off
date.timezone = Asia/Kolkata
memory_limit = 128M

Ubuntu's packages already set expose_php = Off; upstream's production file does not, so without this line every response would carry an X-Powered-By header with the PHP version.

You do not need to configure PHP-FPM itself. The image's docker.conf sets listen = 9000 on all interfaces of the container, sends logs to the container's output, and sets clear_env = no, so the environment variables from Compose reach PHP's getenv(). Workers run as www-data.

Step 4: Nginx talks to PHP over the network

docker/nginx/default.conf replaces the image's welcome site:

Text
server {
    listen 80;
    server_name _;

    root /var/www/app/public;
    index index.php;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ /\.(?!well-known/) {
        deny all;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass php:9000;
    }
}

Compare it with Ubuntu's version from Connecting Nginx to PHP-FPM:

  • fastcgi_pass php:9000 uses the service name instead of a socket. Docker's built-in DNS turns php into the container's address.
  • The image from nginx.org has no Ubuntu snippets/fastcgi-php.conf, so the two important lines are written out. try_files $uri =404 checks the script exists before PHP is asked, the same protection as Ubuntu's snippet. fastcgi_params does not set SCRIPT_FILENAME, so the next line adds it; without it PHP-FPM answers "File not found." and logs "Primary script unknown".
  • SCRIPT_FILENAME is a path inside the PHP container. Both containers mount the code at /var/www/app, so the same path works on both sides.

Nginx looks up php when it starts. If the name cannot be resolved, Nginx refuses to start with "host not found in upstream", which is why web depends on php below.

Step 5: the database's first start

The mysql image runs every .sql file in /docker-entrypoint-initdb.d once, when its data folder is empty, inside the database named by MYSQL_DATABASE. db/init.sql:

SQL
-- Runs once, when the db-data volume is empty.
CREATE TABLE cakes (
    id           INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name         VARCHAR(80) NOT NULL,
    price_rupees INT UNSIGNED NOT NULL
) ENGINE=InnoDB;

INSERT INTO cakes (name, price_rupees) VALUES
    ('Plum cake (500 g)', 450),
    ('Black forest cake (1 kg)', 899),
    ('Tender coconut cake (1 kg)', 1099);

-- The image gave the app user ALL on this database; keep only what the app needs.
REVOKE ALL PRIVILEGES ON kochibakery.* FROM 'kochibakery_app'@'%';
GRANT SELECT, INSERT, UPDATE, DELETE ON kochibakery.* TO 'kochibakery_app'@'%';

The last two lines matter. When you set MYSQL_USER, the image's entry script creates 'kochibakery_app'@'%' and grants it ALL on the database before running your files. That user could drop tables. The REVOKE and GRANT bring it down to the same four privileges as the bakery's user in MySQL Setup, Users & Security. The % host is normal here: connections come from other containers, whose addresses change.

Step 6: compose.yaml

YAML
name: kochibakery

services:
  web:
    image: nginx:1.30
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - ./app/public:/var/www/app/public:ro
    depends_on:
      - php
    restart: unless-stopped

  php:
    build: ./docker/php
    image: kochibakery-php:dev
    environment:
      DB_HOST: db
      DB_NAME: kochibakery
      DB_USER: kochibakery_app
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    volumes:
      - ./app:/var/www/app:ro
    depends_on:
      db:
        condition: service_healthy
        restart: true
    restart: unless-stopped

  db:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: kochibakery
      MYSQL_USER: kochibakery_app
      MYSQL_PASSWORD_FILE: /run/secrets/db_password
      MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
    secrets: [db_password, db_root_password]
    volumes:
      - db-data:/var/lib/mysql
      - ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "--silent"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 30s
    restart: unless-stopped

secrets:
  db_password:
    file: ./secrets/db_password.txt
  db_root_password:
    file: ./secrets/db_root_password.txt

volumes:
  db-data:

The decisions, service by service:

  • web is the only service with ports, the single entrance. 127.0.0.1:8080:80 publishes it on the host's loopback address only. On Linux, ports that Docker publishes skip ufw rules, as Networking in Depth explains, so never publish 3306 or 9000. Nginx gets only app/public; it never sees src.
  • php mounts the whole app folder read-only, so a bug in PHP cannot change the code, the same rule as the pools lesson. depends_on with service_healthy waits for MySQL to be ready, and restart: true restarts PHP when Compose restarts the database.
  • db keeps its data in the named volume db-data, which survives docker compose down. The _FILE variables make the image read each password from its secret file. The healthcheck asks mysqladmin ping over TCP. During the first start the image runs a temporary server without networking while it loads init.sql, so the check passes only when the real server is up.

Step 7: the PHP code

app/src/db.php builds the connection from the environment. It reads the password from the secret file instead of a variable:

PHP
<?php
declare(strict_types=1);

// One PDO connection, built from the container's environment.
function db(): PDO
{
    static $pdo = null;
    if ($pdo === null) {
        $password = trim((string) file_get_contents((string) getenv('DB_PASSWORD_FILE')));
        $dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', getenv('DB_HOST'), getenv('DB_NAME'));
        $pdo = new PDO($dsn, (string) getenv('DB_USER'), $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
    }
    return $pdo;
}

function e(string|int $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

trim() removes the newline that openssl rand wrote at the end of the file. app/public/index.php lists the cakes:

PHP
<?php
declare(strict_types=1);

require dirname(__DIR__) . '/src/db.php';

$cakes = db()->query('SELECT name, price_rupees FROM cakes ORDER BY price_rupees')->fetchAll();
?>
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>Kochi Bakery menu</title>
</head>
<body>
  <h1>Kochi Bakery menu</h1>
  <ul>
<?php foreach ($cakes as $cake): ?>
    <li><?= e($cake['name']) ?>: ₹<?= number_format($cake['price_rupees']) ?></li>
<?php endforeach; ?>
  </ul>
</body>
</html>

app/public/health.php answers monitoring tools with JSON, and with status 503 when the database is unreachable:

PHP
<?php
declare(strict_types=1);

require dirname(__DIR__) . '/src/db.php';

header('Content-Type: application/json');
try {
    $db = db()->query('SELECT VERSION()')->fetchColumn();
    echo json_encode(['php' => PHP_VERSION, 'mysql' => $db]), "\n";
} catch (PDOException) {
    http_response_code(503);
    echo json_encode(['error' => 'database unavailable']), "\n";
}

Step 8: start and test

Build the PHP image, start everything in the background, and wait until the services are running and healthy:

Terminal
docker compose up -d --build --wait
docker compose ps --format "table {{.Service}}\t{{.Status}}\t{{.Ports}}"

The first start takes longer, because MySQL creates its data files and runs init.sql; --wait returns only when db reports healthy. docker compose ps should then list db as Up ... (healthy), and web with 127.0.0.1:8080->80/tcp. Now open the menu:

Terminal
curl -s http://127.0.0.1:8080/
Output
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>Kochi Bakery menu</title>
</head>
<body>
  <h1>Kochi Bakery menu</h1>
  <ul>
    <li>Plum cake (500 g): ₹450</li>
    <li>Black forest cake (1 kg): ₹899</li>
    <li>Tender coconut cake (1 kg): ₹1,099</li>
  </ul>
</body>
</html>

Then the health page and the protections:

Terminal
curl -s http://127.0.0.1:8080/health.php
for path in /.env /missing.php; do
    printf '%-14s' "$path"
    curl -s -o /dev/null -w "%{http_code}\n" "http://127.0.0.1:8080$path"
done
Output
{"php":"8.5.12","mysql":"8.4.13"}
/.env         403
/missing.php  404

The versions are the ones in the images checked for this lesson. A missing PHP file gets 404 from Nginx before PHP is asked. Finally, check the app user's privileges as MySQL's root. The sh -c runs inside the container, where the secret file lives:

Terminal
docker compose exec db sh -c 'mysql -uroot -p"$(cat /run/secrets/db_root_password)" -e "SHOW GRANTS FOR kochibakery_app"'
Output
mysql: [Warning] Using a password on the command line interface can be insecure.
+----------------------------------------------------------------------------------+
| Grants for kochibakery_app@%                                                     |
+----------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `kochibakery_app`@`%`                                      |
| GRANT SELECT, INSERT, UPDATE, DELETE ON `kochibakery`.* TO `kochibakery_app`@`%` |
+----------------------------------------------------------------------------------+

USAGE means "may connect, nothing more"; the second line is all the app can do.

Step 9: daily commands

TaskCommand
Follow all logsdocker compose logs -f
PHP errors onlydocker compose logs php
Shell in the PHP containerdocker compose exec php bash
Apply a changed Dockerfiledocker compose up -d --build
Stop, keeping the datadocker compose down
Back up the databasedocker compose exec -T db sh -c 'mysqldump -uroot -p"$(cat /run/secrets/db_root_password)" --single-transaction kochibakery' > kochibakery.sql

Logs need no files: the Nginx image links its access and error logs to the container's output, and the PHP image sends FPM and worker output there too, so docker compose logs shows both. Changes to files under app/ appear at once, because the code is mounted, not copied into the image. -T in the backup turns off the terminal, so only the dump goes into the file.

Step 10: staging behind the server's Nginx

On the course's Ubuntu server, this stack makes a good staging site: a private copy where Meera tests a change before it reaches customers. The containers publish on 127.0.0.1:8080, which the internet cannot reach, and the host's Nginx adds HTTPS in front, exactly as for Node.js in Nginx as a Reverse Proxy for Node.js. Get a certificate with sudo certbot certonly --nginx -d staging.kochibakery.example.com, then create /etc/nginx/sites-available/staging-kochibakery.conf:

Text
server {
    listen 80;
    listen [::]:80;
    server_name staging.kochibakery.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name staging.kochibakery.example.com;

    ssl_certificate     /etc/letsencrypt/live/staging.kochibakery.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/staging.kochibakery.example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    include snippets/security-headers.conf;
    add_header X-Robots-Tag "noindex, nofollow" always;

    access_log /var/log/nginx/staging-kochibakery.access.log;
    error_log  /var/log/nginx/staging-kochibakery.error.log;

    location / {
        proxy_pass http://127.0.0.1:8080;
        include proxy_params;
    }
}

Link it into sites-enabled and run sudo nginx -t && sudo systemctl reload nginx. X-Robots-Tag asks search engines not to index the staging copy, so it never competes with the real site. For a staging site that only your team should see, add allow lines for your office address and deny all; inside location /.

Common mistakes

  • Publishing 3306:3306 or 9000:9000. Docker's published ports bypass ufw; only web should have ports, and only on 127.0.0.1 when a host proxy is in front.
  • fastcgi_pass 127.0.0.1:9000 inside the web container. 127.0.0.1 is the Nginx container itself; use the service name php.
  • Different code paths in the two containers. SCRIPT_FILENAME must be valid inside the PHP container.
  • Editing init.sql and expecting a change. It runs only on an empty volume.
  • Secret files with mode 600. The bind mount keeps host ownership, so MySQL and PHP inside the containers cannot read them.

Interview questions

1. How does Nginx in one container reach PHP-FPM in another?

Both services are on the network Compose creates for the project, where Docker's DNS resolves each service name to its container. Nginx uses fastcgi_pass php:9000;, and PHP-FPM in the official image listens on port 9000 on all container interfaces. The port is never published to the host.

2. Why must SCRIPT_FILENAME match a path inside the PHP container?

Nginx only forwards the path; PHP-FPM opens the file in its own filesystem. If the code is mounted at different paths, PHP-FPM cannot find the script and returns "File not found." Mounting the code at the same path in both containers avoids it.

3. How do you pass database passwords to official MySQL and PHP containers safely?

Use Compose secrets backed by files that are not in Git. The MySQL image supports MYSQL_PASSWORD_FILE and MYSQL_ROOT_PASSWORD_FILE, and the app reads the same file from /run/secrets/. Secrets do not appear in docker inspect output the way environment variables do.

4. What does depends_on with condition: service_healthy add?

Compose waits until the dependency's healthcheck passes before starting the dependent service. Without a condition, Compose only waits for the container to start, so PHP could try to connect while MySQL is still initialising.

5. When do scripts in /docker-entrypoint-initdb.d run?

Only when the MySQL container starts with an empty data directory, after the database and user from the environment are created. They do not run again while the volume exists.

Key points

  • Three services: web (nginx:1.30), php (built from php:8.5-fpm with pdo_mysql) and db (mysql:8.4).
  • Nginx reaches PHP with fastcgi_pass php:9000, and both containers mount the code at the same path.
  • Only web publishes a port, bound to 127.0.0.1; Docker's published ports bypass ufw.
  • Passwords live in secret files read through MYSQL_*_FILE and DB_PASSWORD_FILE, never in Git.
  • init.sql runs once on an empty volume; use it to trim the app user to four privileges.
  • A healthcheck plus depends_on: condition: service_healthy starts PHP only when MySQL is ready.
  • On the server, run the stack as a staging site behind the host's Nginx and HTTPS.

Exercise

Add the bakery's orders table and a small order form to this project. Put the table in a second file, db/02-orders.sql, and mount it next to init.sql. Then explain why the table does not appear when you run docker compose up -d on the existing stack, and give two ways to apply it: one that keeps the existing data and one that starts fresh.

Show solution

Create db/02-orders.sql with the orders table from the app lesson, and add a mount under db:

YAML
- ./db/02-orders.sql:/docker-entrypoint-initdb.d/02-orders.sql:ro

The entry script runs files in /docker-entrypoint-initdb.d only when /var/lib/mysql is empty, and the db-data volume already holds a database. To keep the data, run the file once by hand:

Terminal
docker compose exec -T db sh -c 'mysql -uroot -p"$(cat /run/secrets/db_root_password)" kochibakery' < db/02-orders.sql

To start fresh, back up first, then run docker compose down -v and docker compose up -d --wait; both files run in name order on the empty volume. The 02- prefix keeps them in the right order, so the cakes table exists before orders refers to it.

Quick Quiz

1. Which fastcgi_pass line lets the Nginx container reach PHP-FPM in this project?

2. Why does only the web service have a ports entry?

3. You changed db/init.sql, but the new table is missing after docker compose up -d. Why?

4. Why are the secret files given mode 644 inside a 700 folder?

Learn LEMP Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call