Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 111 ยท Language Recipes

Containerizing a PHP App

Containerize a PHP application with Docker: php-fpm plus nginx in Compose, Composer in a build stage, OPcache settings, extensions, non-root users and Laravel tips.

PHP is the odd one among web languages. A Node or Go program is a long-running process that speaks HTTP itself. A classic PHP application is a set of scripts that a web server hands to a PHP process for every request. In Docker that split becomes two containers: nginx, which speaks HTTP and serves static files, and php-fpm, which runs your code. They talk over a small protocol called FastCGI on port 9000.

This lesson builds a small but realistic PHP application image: Composer dependencies resolved in a build stage, the PHP extensions you need, OPcache tuned for production, a non-root process, and a Compose file that wires nginx to php-fpm. Everything is verified with PHP 8.4. At the end you get the pitfalls that affect Laravel and Symfony apps. If Compose is new to you, skim Introduction to Docker Compose first.

How the pieces fit

TEXT
 browser --HTTP--> [ web: nginx ] --FastCGI :9000--> [ app: php-fpm ]
                    serves /public files             runs index.php
                    port 80 (published)              port 9000 (internal only)
                          \_______ same Compose network ______/

Two images, one network. nginx finds php-fpm by its service name (app), thanks to Docker's built-in DNS on Compose networks (see User-Defined Bridge Networks). Only nginx publishes a port to the host; nobody outside should ever talk FastCGI to php-fpm directly.

An alternative is a single container that runs both (Apache with mod_php, or FrankenPHP). That is simpler to start with, but the nginx-plus-fpm pair is the most widespread production layout, scales the PHP part independently, and is what most hosting guides assume.

The sample application

The app is deliberately small. composer.json requires one real library (Monolog), so the build has something to install:

JSON
{
  "name": "example/hello-php",
  "require": {
    "php": "^8.4",
    "monolog/monolog": "^3.0"
  },
  "autoload": {
    "psr-4": { "App\\": "src/" }
  }
}

public/index.php is the single entry point (the "front controller"). It has three routes: a greeting, /health, and /opcache, which reports the cache state so you can see it work:

PHP
<?php

require __DIR__ . '/../vendor/autoload.php';

use App\Greeter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

$log = new Logger('app');
$log->pushHandler(new StreamHandler('php://stderr'));

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if ($path === '/health') {
    header('Content-Type: text/plain');
    echo "ok\n";
    exit;
}

if ($path === '/opcache') {
    header('Content-Type: text/plain');
    $status = opcache_get_status(false);
    echo 'opcache enabled: ', var_export($status['opcache_enabled'] ?? false, true), "\n";
    echo 'cached scripts: ', $status['opcache_statistics']['num_cached_scripts'] ?? 0, "\n";
    exit;
}

$log->info('request', ['path' => $path]);
header('Content-Type: text/plain');
echo (new Greeter())->greet('Docker'), "\n";

src/Greeter.php is a trivial class (App\Greeter::greet() returns "Hello, {$name}, from PHP " . PHP_VERSION). Note that logs go to php://stderr: in a container, write logs to stdout or stderr, never to files, so docker logs can show them (see Logs and exec).

Run composer update once (on your machine, or in a throwaway container) to create composer.lock, and commit it. The lock file is what makes the Docker build reproducible.

The Dockerfile: three targets

One Dockerfile can produce both images. Each final stage is a target, selected with target: in Compose:

DOCKERFILE
# ---- 1. Composer dependencies (no dev packages) ----
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY src ./src
RUN composer dump-autoload --classmap-authoritative --no-dev

# ---- 2. PHP-FPM application image ----
FROM php:8.4-fpm-alpine AS app
RUN docker-php-ext-install -j"$(nproc)" opcache
COPY opcache.ini /usr/local/etc/php/conf.d/opcache.ini
WORKDIR /var/www/html
COPY --from=vendor /app/vendor ./vendor
COPY src ./src
COPY public ./public
USER www-data
EXPOSE 9000

# ---- 3. nginx image that serves the static files and forwards PHP ----
FROM nginx:alpine AS web
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY public /var/www/html/public

Step by step:

  1. Stage vendor uses the official composer:2 image (316 MB in our pull). It never reaches production; it only produces the vendor/ directory. Copying composer.json and composer.lock first means the slow composer install layer is cached until your dependencies change. --no-dev leaves out test tools. --classmap-authoritative builds a class map so the autoloader never touches the disk to look for a class, which is faster.
  2. Stage app starts from php:8.4-fpm-alpine (130 MB). In PHP 8.4 the OPcache extension is shipped but not built, so we compile it with the helper docker-php-ext-install. That compile is the slowest step of the build (about three minutes on our machine), and since it comes before the COPY of your code, it stays cached across ordinary code changes. Put slow, rarely changing steps first.
  3. Stage web is plain nginx with your config and a copy of public/, so nginx can serve images, CSS and JavaScript itself without bothering PHP.

Add a .dockerignore so vendor/ from your laptop (which may contain dev packages and different platform builds) never enters the build context:

TEXT
vendor
.git
compose.yaml
Dockerfile

OPcache settings

PHP normally parses and compiles every script on every request. OPcache keeps the compiled form in shared memory. In production it is the single biggest PHP speed-up. The file opcache.ini:

INI
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0
opcache.jit=off

validate_timestamps=0 tells PHP never to check whether a file changed on disk. That is correct inside an immutable image (the code can only change by deploying a new container) and saves a stat call per file per request. It is also the classic development trap: if you bind-mount your source and edit it, nothing changes until the container restarts. Use a separate setting for development (opcache.validate_timestamps=1, or docker compose watch, see Compose for Development).

The nginx configuration

NGINX
server {
    listen 80;
    root /var/www/html/public;
    index index.php;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass app:9000;
        fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
        include fastcgi_params;
    }

    location ~ \.php$ {
        return 404;
    }
}

Read it from the top: real files in public/ are served directly; everything else is rewritten to index.php; only index.php is ever passed to PHP (fastcgi_pass app:9000, where app is the Compose service name); any other .php URL is a 404. That last block matters: forwarding arbitrary .php requests is how uploaded files get executed.

SCRIPT_FILENAME is the path as php-fpm sees it. nginx and php-fpm are different containers, but both images contain the code at /var/www/html/public, so the path is valid on both sides. If you mount code at different paths in the two containers, requests fail with "File not found." and the fpm log says Primary script unknown.

The Compose file

YAML
services:
  app:
    image: tcd-b13-php-app
    build:
      context: .
      target: app
    restart: unless-stopped

  web:
    image: tcd-b13-php-web
    build:
      context: .
      target: web
    ports:
      - "127.0.0.1:18434:80"
    depends_on:
      - app
    restart: unless-stopped

(In your project use your own image names and a port like 127.0.0.1:8080:80.) Only web publishes a port, bound to 127.0.0.1 so it is not exposed to your network by accident (see Publishing Ports). Build and start:

CONSOLE
$ docker compose build
$ docker images --format '{{.Repository}} {{.Size}}'
app 133MB
web 93.6MB
$ docker compose up -d
 Container web-1 Creating
 Container web-1 Created
 Container app-1 Starting
 Container app-1 Started
 Container web-1 Starting
 Container web-1 Started

The application image is 133 MB, only 3 MB more than the plain php:8.4-fpm-alpine base, and it contains no Composer, no compiler, no tests. Now talk to it:

CONSOLE
$ curl -s 127.0.0.1:8080/
Hello, Docker, from PHP 8.4.27
$ curl -s 127.0.0.1:8080/health
ok
$ curl -s 127.0.0.1:8080/opcache
opcache enabled: true
cached scripts: 26
$ curl -s -o /dev/null -w '%{http_code}\n' 127.0.0.1:8080/vendor/autoload.php
404

cached scripts: 26 are the files OPcache compiled so far (your code plus Composer and Monolog files). The last request shows that PHP files outside the front controller cannot be reached from the web. Look at the logs; Compose merges both services with a prefix:

CONSOLE
$ docker compose logs app
app-1  | [23-Oct-2026 15:31:49] NOTICE: [pool www] 'user' directive is ignored when FPM is not running as root
app-1  | [23-Oct-2026 15:31:49] NOTICE: [pool www] 'group' directive is ignored when FPM is not running as root
app-1  | [23-Oct-2026 15:31:49] NOTICE: fpm is running, pid 1
app-1  | [23-Oct-2026 15:31:49] NOTICE: ready to handle connections
app-1  | [2026-10-23T15:31:52.823187+00:00] app.INFO: request {"path":"/"} []

The two NOTICE lines are harmless. They appear because we run as www-data instead of root, and php-fpm's pool configuration asks to switch to that user, which it cannot (and need not) do. The last line is our Monolog message on stderr, visible in docker logs. The process list confirms the user and that FPM is PID 1:

CONSOLE
$ docker compose exec app ps
PID   USER     TIME  COMMAND
    1 www-data  0:00 php-fpm: master process (/usr/local/etc/php-fpm.conf)
    6 www-data  0:00 php-fpm: pool www
    7 www-data  0:00 php-fpm: pool www

Finally, you can see PHP's view of the extensions and the active OPcache settings:

CONSOLE
$ docker compose exec app php -m | grep -i opcache
Zend OPcache
Zend OPcache
$ docker run --rm app php -i | grep -E "^opcache.validate_timestamps|^memory_limit"
memory_limit => 128M => 128M
opcache.validate_timestamps => Off => Off

PHP extensions

The official PHP image includes only a core set of extensions. Real applications nearly always need more: pdo_mysql, pdo_pgsql, bcmath, gd, intl, zip, redis. Add the ones you need in the app stage. Built-in extensions use the helper script:

DOCKERFILE
FROM php:8.4-fpm-alpine
RUN docker-php-ext-install pdo_mysql bcmath

We built that image and listed its modules:

CONSOLE
$ docker run --rm php-ext php -m | grep -iE "pdo_mysql|bcmath"
bcmath
pdo_mysql

Extensions that need system libraries (gd, intl, zip) also need the Alpine -dev packages at build time and the runtime libraries afterwards. A widely used shortcut is the community script install-php-extensions, which works out those packages for you (read-only example, not run here):

DOCKERFILE
COPY --from=ghcr.io/mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/
RUN install-php-extensions gd intl zip redis

For PECL extensions such as redis the official image documents pecl install followed by docker-php-ext-enable; the script just automates that.

php.ini: development and production

The official image ships with no php.ini, only two templates. Choose one per environment, and put your own tweaks in conf.d/:

CONSOLE
$ docker run --rm app ls /usr/local/etc/php
conf.d
php.ini-development
php.ini-production
DOCKERFILE
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"

The production template turns display_errors off (errors must never be shown to visitors) and logs instead. Without any php.ini, as in our sample, display_errors defaults to STDOUT, which is a mistake for a public site.

Laravel and Symfony notes

Everything above applies directly to frameworks. The extra points (a read-only checklist; adapt to your project):

  • Copy composer.json, composer.lock and, for Laravel, the artisan and bootstrap files the install scripts need, or use --no-scripts and run composer run-script post-autoload-dump once the whole tree is present.
  • Writable directories: Laravel writes to storage/ and bootstrap/cache/; Symfony to var/. As a non-root user, chown them in the image (COPY --chown=www-data:www-data or RUN chown -R www-data storage bootstrap/cache). Better still, send logs to stderr and sessions or cache to Redis, so only temporary files need a writable path (a tmpfs, see tmpfs and In-Memory Storage).
  • Build-time optimization: php artisan config:cache route:cache view:cache (Laravel) or composer dump-env prod (Symfony). Never bake secrets into these cached files; set real configuration through environment variables at run time (see Configuring Containers).
  • Queue workers and the scheduler use the same image with a different command (php artisan queue:work, or a loop running php artisan schedule:run). In Compose that is another service with command: set.
  • Run migrations as a one-off command (docker compose run --rm app php artisan migrate --force), not in the container's entrypoint, or every replica will race to migrate at start.
  • Databases and Redis are separate services with their own volumes. See Running Databases in Containers.

Common mistakes

  • Mixing up the two paths. nginx needs the static files; php-fpm needs the scripts. Building both from the same context, as here, keeps them in sync. Sharing a volume between them is fragile because a named volume is populated only once.
  • Leaving port 9000 published. FastCGI has no authentication. Keep it on the internal network.
  • Running as root. The USER www-data line costs nothing. Check that your application can still write where it must.
  • Development settings in production. display_errors=On, Xdebug installed, and validate_timestamps=1 slow things down and leak information. Use build arguments or a separate target for a development image.
  • One huge image with everything. Keep Composer, Node and build tools in build stages. See Multi-Stage Builds.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a typical PHP deployment use two containers, nginx and php-fpm?

    A classic PHP app is a set of scripts executed per request. The web server handles HTTP and static files and forwards PHP requests to php-fpm on port 9000 via FastCGI. Splitting them lets you scale and secure each part separately.
  2. 2. In the Compose file, how does nginx find php-fpm with fastcgi_pass app:9000?

    Compose puts both services on a network with automatic DNS, so the service name is the host name. Port 9000 is not published to the host at all; it is only reachable inside the network.
  3. 3. What is the downside of opcache.validate_timestamps=0 during development?

    With timestamp validation off, PHP never checks whether a file changed, which is right for an immutable production image and wrong when you edit source live. Enable validation (or restart/rebuild) for development.
  4. 4. Why is the nginx location ~ .php$ { return 404; } block included?

    Only the front controller index.php may be handled by PHP. In our test, a request for /vendor/autoload.php returned 404 instead of being executed.
  5. 5. Where should the application write its logs in a container?

    Docker collects each container's stdout and stderr. Our Monolog handler writes to php://stderr and the entry shows up in docker compose logs app.

Summary

  • A PHP stack is usually two containers: nginx (HTTP, static files) and php-fpm (runs scripts), connected over FastCGI on the Compose network. Publish only nginx, and bind it to 127.0.0.1 unless you mean to expose it.
  • Resolve Composer dependencies in a build stage (composer install --no-dev, --classmap-authoritative), copy composer.json and the lock file first for caching, and ship only vendor/ and your code.
  • Install extensions with docker-php-ext-install (or install-php-extensions) before copying your code, so the slow step stays cached.
  • Enable OPcache with validate_timestamps=0 in production; remember that this hides file edits during development. Pick php.ini-production and never show errors to visitors.
  • Run as www-data, send logs to stderr, forward only index.php to PHP, and keep port 9000 internal.
  • For Laravel and Symfony, make storage or var writable, cache config at build time, run workers from the same image, and run migrations as one-off commands.

Next: Containerizing a .NET App