A Dockerfile that works fine for local development (a single image, php artisan serve, the source code mounted as a volume) quickly becomes a liability in production: a multi-gigabyte image, build-time dependencies baked into the final image, migrations triggered unpredictably on container startup, configuration caches that never get regenerated after a deploy. Dockerizing for production is not the same task as dockerizing for development comfort, and the two deserve separate Dockerfiles rather than one file full of conditional branches.

Why the dev image should never ship to production

A typical development image installs Composer, Node, debug PHP extensions (Xdebug), and mounts the code as a volume for hot reload. If that same image goes to production:

  • It ships Composer's dev dependencies (--dev) and sometimes Node build tooling, which bloats the image and widens the attack surface.
  • It recomputes the autoloader and configuration caches on every container start instead of having them pre-generated at build time, which slows down every deploy and every horizontal scale-out event.
  • It usually has no separation between the web server and the PHP runtime, which prevents scaling the two independently.

A multi-stage build fixes the first point by explicitly separating the build environment (Composer, compilation tools) from the final image, which only contains the strictly necessary runtime.

Multi-stage Dockerfile for Laravel

# syntax=docker/dockerfile:1

# --- Stage 1: Composer dependencies (no dev packages) ---
FROM composer:2.7 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install \
    --no-dev \
    --no-interaction \
    --no-scripts \
    --optimize-autoloader \
    --no-plugins

# --- Stage 2: frontend asset build (Vite/Mix) ---
FROM node:20-alpine AS assets
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY resources resources
COPY vite.config.js ./
RUN npm run build

# --- Stage 3: final PHP-FPM image ---
FROM php:8.3-fpm-alpine AS production

RUN apk add --no-cache icu-dev libzip-dev oniguruma-dev postgresql-dev \
    && docker-php-ext-install pdo_pgsql opcache intl zip bcmath

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

WORKDIR /var/www/html

RUN composer dump-autoload --optimize --classmap-authoritative --no-dev \
    && php artisan config:cache \
    && php artisan route:cache \
    && php artisan view:cache

RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache

USER www-data
EXPOSE 9000
CMD ["php-fpm"]

A few details worth calling out:

  • --no-scripts on the first composer install: running Composer scripts (often tied to artisan) before the application code is copied in would break the build, since artisan doesn't exist yet at that stage.
  • php artisan config:cache baked into the image, not run at container startup: a common mistake is running these commands from an entrypoint on every start. The problem is that config:cache freezes environment variable values at the moment the cache is built; if the same image is built once and deployed across several environments with different .env files, that cache will carry the wrong values. The correct approach is either to build one image per environment with the right variables injected at build time, or to run config:cache from the entrypoint only if environment variables are injected at runtime (the usual case with Kubernetes/ECS).
  • opcache: the extension is installed here but still needs a dedicated opcache.ini that enables opcache.validate_timestamps=0 in production, which avoids recomputing file checksums on every request.

Separating Nginx and PHP-FPM instead of an all-in-one container

A container that runs both Nginx and PHP-FPM through a process supervisor (supervisord) simplifies the initial setup but prevents scaling the two components independently and complicates log collection (two processes writing to the same stdout). For a serious containerized architecture, Nginx and PHP-FPM are two separate services talking over FastCGI:

# docker-compose.yml (production topology example, later orchestrated by k8s/ECS for real)
services:
  nginx:
    image: nginx:1.25-alpine
    volumes:
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - static_assets:/var/www/html/public:ro
    ports:
      - "8080:80"
    depends_on:
      - app

  app:
    build:
      context: .
      target: production
    volumes:
      - static_assets:/var/www/html/public
    environment:
      - APP_ENV=production
    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine

volumes:
  static_assets:
  pgdata:

The Nginx configuration forwards to app:9000 over FastCGI rather than serving PHP directly:

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

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

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

The Symfony case: same principles, different caching mechanism

For Symfony, the split is identical (multi-stage build, separate Nginx/PHP-FPM), but the caching mechanism differs: bin/console cache:warmup --env=prod must run after composer install --no-dev and before the image is finalized, with APP_ENV=prod explicitly set so the warmup generates the right cache (Symfony's dev and prod caches live in different directories and are not interchangeable).

FROM php:8.3-fpm-alpine AS production
# ... same extensions as the Laravel example ...

COPY --from=vendor /app/vendor /var/www/html/vendor
COPY . /var/www/html
WORKDIR /var/www/html

ENV APP_ENV=prod
RUN composer dump-autoload --optimize --classmap-authoritative --no-dev \
    && php bin/console cache:clear --env=prod --no-debug \
    && php bin/console cache:warmup --env=prod --no-debug

RUN chown -R www-data:www-data var/cache var/log
USER www-data
EXPOSE 9000
CMD ["php-fpm"]

Database migrations: never in the application container's CMD

A frequent trap is running php artisan migrate or php bin/console doctrine:migrations:migrate from the application container's ENTRYPOINT. The problem surfaces as soon as you scale horizontally: if three replicas start at the same time after a deploy, all three trigger the migration simultaneously, which can create race conditions on non-idempotent migrations (a column added twice, a concurrent table lock).

The robust approach is to treat migrations as a separate, single deployment step, for example a dedicated Kubernetes Job or an explicit CI/CD pipeline stage, run exactly once before the new application pods are brought up:

# CI stage example (GitLab CI)
migrate:
  stage: deploy
  script:
    - docker run --rm --env-file .env.production $IMAGE php artisan migrate --force
  environment:
    name: production

Image size and layer caching

A multi-stage build already avoids shipping Composer and Node inside the final image, but layer ordering inside the Dockerfile still determines how often the build cache gets invalidated. Copying the entire application source before running composer install forces Docker to reinstall every dependency on every code change, since any file change invalidates that layer and everything after it:

# Slow: any source change invalidates the composer install layer
COPY . /app
RUN composer install --no-dev

# Fast: dependencies only reinstall when composer.lock actually changes
COPY composer.json composer.lock /app/
RUN composer install --no-dev --no-scripts
COPY . /app
RUN composer dump-autoload --optimize --no-dev

The same principle applies to the Node asset stage: copying package.json/package-lock.json first and running npm ci before copying the rest of resources/ keeps the dependency install layer cached across commits that only touch Blade/Twig templates or PHP code, which is the overwhelming majority of commits on a typical project. On a CI pipeline building dozens of times a day, this difference alone can cut several minutes off every build.

Image size itself also matters beyond aesthetics: a smaller image pulls faster during a rolling deployment, which shortens the window during which old and new pods run side by side under a Kubernetes RollingUpdate. Switching from php:8.3-fpm (Debian-based, roughly 450MB with common extensions) to php:8.3-fpm-alpine (roughly 90MB) is usually the single biggest win, at the cost of occasionally needing to track down an Alpine-specific package name (musl instead of glibc means some PECL extensions need different build flags).

Hardening the runtime container

A few additional measures separate a container that merely works from one that's reasonably hardened for a production environment handling real traffic:

# Drop to a non-root user as early as the base image allows,
# and make the filesystem read-only everywhere writes aren't needed
RUN addgroup -g 1000 app && adduser -D -u 1000 -G app app
USER app

# docker run / Kubernetes securityContext equivalent:
# readOnlyRootFilesystem: true, with explicit writable mounts
# for storage/, bootstrap/cache/ (Laravel) or var/ (Symfony)

Running as a non-root user limits the blast radius of a remote code execution vulnerability in a PHP dependency, since the compromised process can't write outside its own user's permissions. A read-only root filesystem goes further by preventing any write to the application code itself at runtime, forcing an attacker who achieves code execution to work entirely in memory; Laravel's storage/ and bootstrap/cache/ directories (or Symfony's var/) need to be mounted as explicitly writable volumes or tmpfs mounts for this to work without breaking the framework.

What the Dockerfile alone doesn't solve

Dockerizing the application correctly solves neither session handling (which should move to Redis instead of the local filesystem as soon as there's more than one replica, or users will get randomly logged out), nor uploaded file storage (which should go to S3/object storage rather than a local volume not shared across replicas), nor healthcheck configuration (Docker's HEALTHCHECK or Kubernetes probes should target a real application endpoint, not just confirm PHP-FPM is responding). These are independent of the Dockerfile itself and need to be addressed explicitly in the application configuration before the move to containers can be considered done.

Takeaway

A production Dockerfile is built in multiple stages to keep build-time dependencies out of the final image, pre-generates configuration caches at build time rather than on startup, and separates Nginx from PHP-FPM to allow independent scaling. Database migrations fall outside the application container's lifecycle and become a single, explicit deployment step, never a reflex tucked into CMD or an entrypoint script.