Back to blog

Tooling

PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels

Build lean PHP containers with tested Alpine runtimes, multi-stage Dockerfiles, non-root execution, OCI labels, and health checks.

  • PHP
  • Docker
  • Containers
  • Tooling
  • DevOps

SEO Metadata

SEO Title Options

  1. PHP Container Best Practices: Alpine Images, Multi-Stage
  2. PHP Tooling: Practical 2026 Guide
  3. Tooling Playbook: PHP Tooling

Meta Description Options

  1. Learn PHP Tooling with a practical Tooling framework, expert mistakes, implementation steps, examples, FAQ, and schema-ready guidance.
  2. Production Docker guide for PHP - minimal Alpine base images, multi-stage builds, non-root users, and health check configuration.

URL Slug

php-container-best-practices-alpine-images-multi-stage-oci-labels

Focus Keyword

PHP Tooling

Additional LSI Keywords

  • Tooling
  • PHP
  • Docker
  • Containers
  • DevOps
  • PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels
  • production checklist
  • implementation guide
  • best practices
  • architecture decisions
  • testing strategy
  • performance impact

Table of Contents

Article overview

PHP Tooling is the kind of topic that looks simple until it reaches production. Teams usually discover the real cost late: unclear boundaries, weak defaults, hidden maintenance work, and decisions that seemed harmless when the codebase was small.

The problem gets worse when the article, tutorial, or implementation guide only explains the happy path. This guide closes that gap with a practical framework, a comparison table, common mistakes, and a deep technical section you can use while planning real work.

Keep reading for the non-obvious part: the safest implementation is rarely the most impressive-looking one. It is the one your team can debug, test, document, and evolve without turning every future change into archaeology.

Key Takeaways

  • PHP Tooling should be evaluated as a production decision, not only as a syntax or tooling choice.
  • The best implementation keeps responsibilities visible, with clear ownership, tests, documentation, and rollback paths.
  • Search visibility improves when practical depth, structured answers, and expert examples live on the same page.

[IMAGE: A mobile-first technical article layout showing the main concept, decision table, implementation checklist, and FAQ blocks. Alt: PHP Tooling expert guide for Tooling]

What PHP Tooling means

PHP Tooling means applying tooling knowledge to a concrete engineering decision, then turning that decision into reliable code, documentation, and operational behavior. In practice, it combines the topic's core concepts with trade-off analysis, implementation boundaries, testing strategy, and maintenance discipline.

This is the definition worth optimizing for featured snippets because it avoids hype. It tells the reader what the topic does and what a professional implementation must include.

Why it matters now

The technical web is more crowded than it was a few years ago. Thin tutorials can still get indexed, but they rarely earn trust from senior developers, buyers, AI answer systems, or teams that need production guidance.

For tooling topics, the strongest content now has three layers:

  • a clear answer for fast scanning
  • a practical framework for implementation
  • expert context that explains what breaks later

That same structure helps search engines understand the page. It also helps readers decide whether the advice fits their project.

Implementation framework

Use this framework before adopting the approach described in this article.

  1. Define the user problem and the production risk.
  2. Identify the smallest reliable implementation boundary.
  3. Keep configuration, secrets, and environment-specific behavior outside the article's core logic.
  4. Add tests for the behavior that would hurt if it regressed.
  5. Document the trade-off, not only the final code.
  6. Measure the result with logs, metrics, or user-facing outcomes.
  7. Revisit the decision after real usage exposes edge cases.

The sequence is deliberately conservative. It keeps the work grounded in outcomes instead of novelty.

[IMAGE: A seven-step implementation framework with discovery, boundary design, configuration, tests, documentation, measurement, and iteration. Alt: PHP Tooling implementation framework]

Practical comparison

Decision areaStrong approachWeak approachWhy it matters
ScopeSolve one clear problemMix unrelated concernsFocus improves testing and search intent
ArchitecturePut logic in explicit classes or documented boundariesHide behavior in templates or incidental callbacksFuture changes stay easier to review
Data flowPass prepared data into the view or endpointQuery or compute in presentation codeReduces regressions and performance surprises
TestingCover the risky behavior directlyTest only the happy pathCatches production failures earlier
DocumentationExplain trade-offs and limitsRepeat generic definitionsBuilds E-E-A-T and reader trust
OperationsTrack logs, metrics, and rollback stepsShip without measurementMakes the decision reversible

This table is intentionally practical. It gives a reviewer something to check before the implementation becomes expensive to change.

Expert workflow

Expert tip: "Treat PHP Tooling as a system boundary. If the next developer cannot find where the decision lives, how it is tested, and when it should be avoided, the implementation is not finished."

A useful workflow is simple:

  • Start with the smallest working example.
  • Add the constraints that exist in your real project.
  • Remove anything that only demonstrates cleverness.
  • Write down the failure modes.
  • Add links to related decisions so future readers can navigate the topic cluster.

That last point matters for both humans and search systems. A single article can answer a question; a cluster proves authority.

Common mistakes

Mistake 1: Copying a pattern without its context

A pattern that works in a small demo can fail in a real application. The missing context is usually data volume, team experience, deployment process, security requirements, or observability.

Before copying the pattern, ask what assumption made it safe in the original example.

Mistake 2: Putting business logic in the wrong layer

This is the fastest way to make future debugging expensive. In Laravel, PHP, and server-rendered websites, presentation should receive prepared data, not discover rules on its own.

Keep decision logic in models, actions, services, policies, requests, jobs, or documented helpers where it can be tested directly.

Mistake 3: Optimizing for novelty instead of maintainability

Newer tools and language features can be valuable. They can also hide simple behavior behind unfamiliar syntax.

Use the option that makes the next production incident easier to understand.

Mistake 4: Publishing without a measurement plan

If the article describes a performance, SEO, security, or architecture improvement, define how success will be checked. Logs, tests, crawl diagnostics, analytics, and user behavior are all stronger than assumptions.

[IMAGE: A common-mistakes board with context loss, wrong layer, novelty bias, and missing measurement highlighted. Alt: PHP Tooling common mistakes]

Image placeholders

  • [IMAGE: A concept diagram for PHP Tooling with input, decision boundary, implementation, tests, and production feedback. Alt: PHP Tooling concept diagram]
  • [IMAGE: A mobile screenshot-style checklist for PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels. Alt: PHP Tooling mobile checklist]
  • [IMAGE: A comparison table visualization for strong versus weak implementation choices. Alt: PHP Tooling comparison table]

Video placeholder

[VIDEO: Insert a 5-8 minute YouTube walkthrough that demonstrates the main decision, the implementation boundary, the test strategy, and the production caveats for PHP Tooling.]

  • PHP manual - use this as the trust reference for language-level reference.
  • Docker documentation - use this as the trust reference for container runtime reference.

Internal linking opportunities

Original Technical Deep Dive

Most bad PHP production images fail in the same ways:

  • Composer runs in the runtime image.
  • node_modules, build tools, .git, and tests are shipped to production.
  • The app runs as root because nobody changed the default.
  • The image has no useful metadata.
  • The health check proves only that a process exists, not that the app is usable.
  • Alpine is chosen for size even when native extensions need glibc behavior.

A production PHP image should be boring: pinned base, small runtime, repeatable build, non-root process, clear labels, explicit health checks, and no secrets baked into layers.

This guide uses PHP-FPM because it is still the most common production target for Laravel, Symfony, and custom PHP apps. The same principles apply to CLI workers and Octane images.

Target image shape

Use separate stages for separate jobs:

StagePurposeKept in final image
php-basePHP runtime extensions and configYes
vendorComposer install and optimized autoloadOnly vendor/ and generated files
assetsNode/Vite/Webpack buildOnly compiled assets
runtimeFinal FPM imageYes

The final image should contain application code, vendor/, compiled assets, PHP configuration, and only the OS packages needed at runtime.

Start with .dockerignore

Do this before tuning the Dockerfile. A small build context improves cache behavior and prevents accidental leaks.

.git
.github
.env
.env.*
node_modules
vendor
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
tests
coverage
.phpunit.cache
.phpstan
.idea
.vscode
Dockerfile*
compose.yaml
docker-compose*.yml
README.md

Keep docker/ included if it contains PHP config, FPM config, health scripts, or entrypoint scripts.

Choose Alpine deliberately

The official php:<version>-alpine images are small because Alpine is small. That is useful for pull time, registry storage, and attack surface.

The tradeoff is musl libc. Most PHP apps are fine, but some native dependencies are not:

  • proprietary APM agents
  • Oracle or SQL Server drivers
  • some PECL extensions
  • FFI integrations
  • prebuilt binaries expecting glibc
  • image or PDF tooling with deep native dependency trees

Use Alpine when your extension stack is tested on Alpine. Use Debian slim when the native stack is the product risk.

Do not switch base distributions only in production. If production uses Alpine, CI should build and test the Alpine image.

Production Dockerfile

This Dockerfile is intentionally explicit. It installs runtime libraries, compiles PHP extensions in the build layer, removes build dependencies, copies only production artifacts, labels the image, and runs as www-data.

# syntax=docker/dockerfile:1

ARG PHP_VERSION=8.4
ARG ALPINE_VERSION=3.22

FROM composer:2 AS composer-bin

FROM php:${PHP_VERSION}-fpm-alpine${ALPINE_VERSION} AS php-base

WORKDIR /var/www/html

RUN set -eux; \
    apk add --no-cache \
        ca-certificates \
        curl \
        icu-libs \
        libzip \
        oniguruma \
        tzdata; \
    apk add --no-cache --virtual .build-deps \
        $PHPIZE_DEPS \
        icu-dev \
        libzip-dev \
        oniguruma-dev; \
    docker-php-ext-install -j"$(nproc)" \
        intl \
        mbstring \
        opcache \
        pdo_mysql \
        zip; \
    apk del .build-deps; \
    mkdir -p /usr/local/var/log /usr/local/var/run; \
    chown -R www-data:www-data /usr/local/var /var/www/html

COPY docker/php/production.ini /usr/local/etc/php/conf.d/production.ini
COPY docker/php/www.conf /usr/local/etc/php-fpm.d/zz-app.conf

FROM php-base AS vendor

COPY --from=composer-bin /usr/bin/composer /usr/local/bin/composer
COPY composer.json composer.lock ./

RUN --mount=type=cache,target=/tmp/composer-cache \
    COMPOSER_ALLOW_SUPERUSER=1 \
    COMPOSER_CACHE_DIR=/tmp/composer-cache \
    composer install \
        --no-dev \
        --prefer-dist \
        --no-interaction \
        --no-progress \
        --no-scripts

COPY app ./app
COPY bootstrap ./bootstrap
COPY config ./config
COPY database ./database
COPY routes ./routes
COPY artisan ./

RUN COMPOSER_ALLOW_SUPERUSER=1 \
    composer dump-autoload \
        --no-dev \
        --classmap-authoritative

FROM node:22-alpine AS assets

WORKDIR /app

COPY package.json package-lock.json ./

RUN --mount=type=cache,target=/root/.npm \
    npm ci

COPY resources ./resources
COPY public ./public
COPY vite.config.* ./

RUN npm run build

FROM php-base AS runtime

ARG BUILD_DATE
ARG VCS_REF
ARG VERSION=dev

LABEL org.opencontainers.image.title="Example PHP App" \
      org.opencontainers.image.description="Production PHP-FPM container image" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.source="https://github.com/example/app" \
      org.opencontainers.image.revision="${VCS_REF}" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.licenses="MIT"

COPY --chown=www-data:www-data . .
COPY --from=vendor --chown=www-data:www-data /var/www/html/vendor ./vendor
COPY --from=assets --chown=www-data:www-data /app/public/build ./public/build

RUN set -eux; \
    mkdir -p \
        bootstrap/cache \
        storage/app \
        storage/framework/cache \
        storage/framework/sessions \
        storage/framework/views \
        storage/logs; \
    chown -R www-data:www-data bootstrap/cache storage; \
    find bootstrap/cache storage -type d -exec chmod 775 {} \; && \
    find bootstrap/cache storage -type f -exec chmod 664 {} \;

USER www-data:www-data

EXPOSE 9000

HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
    CMD php /var/www/html/docker/health/fpm-port.php || exit 1

CMD ["php-fpm"]

[IMAGE: Supporting visual 1 for PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels, showing PHP Tooling decisions, examples, and PHP, Docker, Containers. Alt: PHP Tooling php-container-best-practices-alpine-images-multi-stage-oci-labels visual 1]

[IMAGE: Supporting visual 1 for PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels, showing PHP Tooling decisions, examples, and PHP, Docker, Containers. Alt: PHP Tooling php-container-best-practices-alpine-images-multi-stage-oci-labels visual 1]

If the app does not build frontend assets, remove the assets stage. If it is a worker image, replace CMD ["php-fpm"] with the worker command and use a worker-specific health check.

PHP configuration

Example docker/php/production.ini:

expose_php = Off
display_errors = Off
log_errors = On
error_reporting = E_ALL
memory_limit = 256M
max_execution_time = 60
upload_max_filesize = 20M
post_max_size = 20M
realpath_cache_size = 4096K
realpath_cache_ttl = 600

opcache.enable = 1
opcache.enable_cli = 0
opcache.validate_timestamps = 0
opcache.memory_consumption = 192
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000
opcache.jit = off

For rolling deploys, opcache.validate_timestamps = 0 is fine when each deploy builds a new immutable image. Do not use it with mutable bind-mounted production code.

Example docker/php/www.conf:

[www]
listen = 0.0.0.0:9000
clear_env = no
catch_workers_output = yes
decorate_workers_output = no

pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
pm.max_requests = 500

ping.path = /fpm-ping
ping.response = pong

Tune pm.max_children from memory measurements, not from CPU count alone. If one worker can use 128 MB and the container limit is 512 MB, pm.max_children = 20 is fantasy.

Health check script

Docker HEALTHCHECK runs inside the container. For a PHP-FPM container, a cheap process-level check can verify that the FPM port accepts connections.

Create docker/health/fpm-port.php:

#!/usr/bin/env php
<?php

declare(strict_types=1);

$socket = @fsockopen('127.0.0.1', 9000, $errno, $error, 1.0);

if (! is_resource($socket)) {
    fwrite(STDERR, sprintf("php-fpm is not reachable: %s (%d)\n", $error, $errno));

    exit(1);
}

fclose($socket);

exit(0);

This proves the FPM process is reachable. It does not prove the database works, migrations are current, or the app can serve a real request.

Use two levels of health:

ProbeWhereWhat it checks
Container healthPHP-FPM imageProcess can accept local FastCGI connections
ReadinessLoad balancer or orchestratorHTTP /up or /ready through Nginx and PHP
Deep diagnosticsInternal admin or scheduled monitorDatabase, Redis, queues, storage, third-party dependencies

Do not put slow dependency checks into a probe that runs every few seconds. That creates outages during dependency incidents instead of reporting them.

Non-root runtime

The example uses USER www-data:www-data because the official PHP images already include that user.

Rules:

  • Build as root when installing packages and extensions.
  • Switch to a non-root user before runtime.
  • Make only required paths writable.
  • Do not make the whole app 777.
  • Do not run Composer or npm at container startup.
  • Do not write cache files outside storage, bootstrap/cache, or your framework's expected writable paths.

If your platform requires a fixed numeric UID, create an app user instead:

ARG APP_UID=10001
ARG APP_GID=10001

RUN addgroup -g "${APP_GID}" -S app \
    && adduser -u "${APP_UID}" -S -D -G app app

USER app:app

When you replace www-data, also adjust file ownership and PHP-FPM pool configuration.

OCI labels

Labels make images traceable. Use OCI label keys so registries and scanners can understand them.

[IMAGE: Supporting visual 2 for PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels, showing PHP Tooling decisions, examples, and PHP, Docker, Containers. Alt: PHP Tooling php-container-best-practices-alpine-images-multi-stage-oci-labels visual 2]

Useful labels:

LABEL org.opencontainers.image.title="Example PHP App" \
      org.opencontainers.image.description="Production PHP-FPM container image" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.source="https://github.com/example/app" \
      org.opencontainers.image.revision="${VCS_REF}" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.licenses="MIT"

Do not put secrets in labels. Labels are image metadata and can be read by anyone with image access.

Build with metadata:

docker buildx build \
  --build-arg BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
  --build-arg VCS_REF="$(git rev-parse HEAD)" \
  --build-arg VERSION="$(git describe --tags --always)" \
  --tag ghcr.io/example/app:$(git rev-parse --short HEAD) \
  --load \
  .

[IMAGE: Supporting visual 2 for PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels, showing PHP Tooling decisions, examples, and PHP, Docker, Containers. Alt: PHP Tooling php-container-best-practices-alpine-images-multi-stage-oci-labels visual 2]

Inspect labels:

docker image inspect ghcr.io/example/app:$(git rev-parse --short HEAD) \
  --format '{{ json .Config.Labels }}'

Cache without leaking dependencies

Layer order matters. Copy lock files before source code so dependency installs are cached until dependencies change:

COPY composer.json composer.lock ./
RUN --mount=type=cache,target=/tmp/composer-cache \
    COMPOSER_CACHE_DIR=/tmp/composer-cache \
    composer install --no-dev --prefer-dist --no-scripts

COPY app ./app
COPY routes ./routes
RUN composer dump-autoload --no-dev --classmap-authoritative

The same applies to npm:

COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

COPY resources ./resources
RUN npm run build

Do not copy the whole repository before composer install unless you want every source-code change to invalidate the dependency layer.

Image tags and digest policy

Use readable tags for humans and immutable references for deployments.

Good tag set:

  • ghcr.io/example/app:1.8.3
  • ghcr.io/example/app:main-2f4c91a
  • ghcr.io/example/app:sha-2f4c91a

For production manifests, deploy a digest:

image: ghcr.io/example/app@sha256:4c4b...

Tags can move. Digests do not. Keep automation that opens dependency update pull requests for base image digest changes instead of silently floating production to whatever a tag points to today.

GitHub Actions build

Use Docker metadata action for tags and OCI labels, then build with Buildx.

name: container

on:
  push:
    branches: [main]
    tags: ['v*.*.*']
  pull_request:

jobs:
  image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        if: github.event_name != 'pull_request'
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: meta
        uses: docker/metadata-action@v6
        with:
          images: ghcr.io/example/app
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=sha-
          labels: |
            org.opencontainers.image.title=Example PHP App
            org.opencontainers.image.description=Production PHP-FPM container image

      - uses: docker/build-push-action@v6
        with:
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: true
          sbom: true

Build the image in pull requests even if you only push it from main. Dockerfiles break quietly when they are not part of CI.

Runtime checks

Run these checks before pushing the image:

docker buildx build --load -t app:test .
docker run --rm app:test php -v
docker run --rm app:test php -m
docker run --rm app:test php -i | grep -E 'opcache.enable|memory_limit'
docker run --rm app:test id
docker image inspect app:test --format '{{ json .Config.User }}'
docker image inspect app:test --format '{{ json .Config.Healthcheck }}'

For Laravel:

docker run --rm --env APP_KEY=base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= app:test php artisan about
docker run --rm --env APP_KEY=base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= app:test php artisan route:list --except-vendor

For Symfony:

docker run --rm --env APP_ENV=prod app:test php bin/console about
docker run --rm --env APP_ENV=prod app:test php bin/console lint:container

Also scan the built image and fail CI on critical vulnerabilities that affect reachable packages. Do not confuse "small image" with "secure image"; a small vulnerable image is still vulnerable.

Common mistakes

Avoid these:

  • FROM php:latest
  • apk add without --no-cache
  • running Composer during container startup
  • copying .env into the image
  • baking production secrets into ARG, ENV, labels, or files
  • shipping build dependencies in the final stage
  • running as root because file permissions are broken
  • storing logs only inside the container filesystem
  • using Alpine without testing native extensions on Alpine
  • using HEALTHCHECK CMD curl http://localhost inside a PHP-FPM-only container
  • treating docker compose development config as the production runtime contract

The container should be an immutable artifact. Runtime configuration comes from the environment, secret manager, mounted secret files, or orchestrator configuration.

[IMAGE: Supporting visual 3 for PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels, showing PHP Tooling decisions, examples, and PHP, Docker, Containers. Alt: PHP Tooling php-container-best-practices-alpine-images-multi-stage-oci-labels visual 3]

Production checklist

Before deploying:

  • Base image is a supported PHP minor version.
  • Base image tag is pinned or tracked by digest update automation.
  • Build context excludes .env, .git, vendor, and node_modules.
  • Composer dependencies are installed with --no-dev.
  • Composer autoload is optimized.
  • Frontend assets are built outside the runtime stage.
  • Build dependencies are removed from the final image.
  • Runtime process uses a non-root user.
  • Writable directories are narrow and owned by the runtime user.
  • OCI labels include source, revision, version, created date, and license.
  • Health checks match the container role.
  • CI builds the image on pull requests.
  • CI scans the final image.
  • Deployment uses immutable tags or digests.

[IMAGE: Supporting visual 3 for PHP Container Best Practices: Alpine Images, Multi-Stage & OCI Labels, showing PHP Tooling decisions, examples, and PHP, Docker, Containers. Alt: PHP Tooling php-container-best-practices-alpine-images-multi-stage-oci-labels visual 3]

Good PHP containers are not clever. They are small, traceable, tested, and replaceable.

FAQ

What is PHP Tooling?

PHP Tooling is a practical tooling topic that should be evaluated through implementation scope, production risk, testing, documentation, and long-term maintainability.

When should a team use PHP Tooling?

Use PHP Tooling when it solves a real project constraint, improves clarity, or reduces operational risk. Avoid it when it only adds novelty or hides behavior from future maintainers.

What is the biggest risk with PHP Tooling?

The biggest risk is copying a pattern without its context. Production systems need clear boundaries, rollback options, tests, and observability before a technique becomes dependable.

How do you test PHP Tooling?

Test the smallest unit that owns the behavior, then add integration coverage for the path users or systems actually rely on. Include failure cases, configuration differences, and regression checks.

How does PHP Tooling affect SEO and AI search visibility?

It improves visibility when the article gives a direct answer, expert context, structured headings, internal links, trustworthy references, and FAQ content that matches the visible page.

Conclusion

PHP Tooling is worth doing when the implementation improves clarity, reliability, or delivery speed. It is not worth doing when it hides ownership, increases operational risk, or makes the system harder to explain.

Use the framework above as a review checklist. Then connect this topic to the rest of the project documentation so readers can move from concept to implementation without losing context.

Top