Exclusive Discount Deal
Upto 50% OFF
Offer ends in:
25 DAYS
|
22 HOURS
|
08 MINS
|
53 SECS
Home / Blog / Docker Multi-Stage Builds: Lean Node and PHP Images
DevOps & Cloud • Oct 6, 2026

Docker Multi-Stage Builds: Lean Node and PHP Images

Best practices for writing lean, secure Dockerfiles, configuring Nginx reverse proxies, and setting up automated CI/CD pipelines.

UPTO 50% OFF
Trending:
BrickTry

Requirement Scope

AI is analyzing your requirement...

Generating custom modules, implementation options, and dynamic clarification questions.

Add Custom Requirement or Module

Add your own specific features, integrations, or components. AI will incorporate them to dynamically generate the next relevant options.

1. Progressive Clarifications

Click to expand & answer

2. Scope Modules & Features (/ Selected)

Click row to expand details · Customize options
✓
✕
Completeness:

Bloated container images remain an unaddressed vulnerability in modern software architecture. Shipping multi-gigabyte runtimes to production environments increases attack surfaces, inflates memory footprints during orchestration scheduling, and bottlenecks continuous deployment pipelines through network serialization latency.

For engineering teams running mixed-stack environments—such as a Next.js administrative frontend coupled with a high-throughput Laravel API backend—optimizing container images is not merely an exercise in hygiene. It is a core requirement for stable Kubernetes scheduling and predictable horizontal auto-scaling.

This guide details how to architect production-ready, highly optimized multi-stage Dockerfiles for both Node.js and PHP runtimes, eliminating build-time dependencies from production images.


The Cost of Single-Stage Monolithic Dockerfiles

Traditional Dockerfiles often rely on a single base image to install dependencies, compile assets, and execute runtime processes. This approach bundles package managers (npm, composer), build utilities (python3, make, gcc), and source code caches into the final artifact.

When deploying a Node.js or PHP application, your production runtime does not require compiler toolchains or development headers. Retaining them introduces two primary risks:

  1. Enlarged Attack Surface: Vulnerability scanners (trivy, snyk) flag thousands of high-severity CVEs originating from unused operating system packages and abandoned development libraries.
  2. Bandwidth Inefficiency: Pushing 1.5GB images to private registries during every blue-green deployment stalls auto-scaling events when traffic spikes unexpectedly.

Multi-Stage Build Architecture

Multi-stage builds allow developers to use multiple FROM instructions in a single Dockerfile. Each FROM instruction starts a new stage with a fresh base image. Crucially, you can selectively copy artifacts from previous stages, leaving behind all build-time dependencies, caches, and intermediate layers.

Architectural Trade-Offs

Metric / Dimension Single-Stage Build Multi-Stage Build
Final Image Size 800MB – 2.5GB 45MB – 180MB
Attack Surface High (Contains compilers, headers, dev tools) Minimal (Strictly runtime binaries & app code)
Build Cache Efficiency Low (Frequent cache invalidation) High (Granular layer separation)
CI/CD Pipeline Latency High (Large pushes/pulls to registry) Low (Lightweight image transfers)

Production-Ready Node.js Multi-Stage Dockerfile

For modern Node.js applications (such as Next.js 15 or NestJS microservices), the separation between build dependencies (devDependencies) and production dependencies (dependencies) is critical.

The following production-grade Dockerfile uses Alpine Linux as the runtime base to minimize resource consumption:

# syntax=docker/dockerfile:1

# Stage 1: Install all dependencies (including devDependencies)
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

# Stage 2: Build the application assets
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Disable telemetry during the build process if applicable
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build

# Stage 3: Production runtime image
FROM node:20-alpine AS runner
WORKDIR /app

ENV NODE_ENV production
ENV PORT 3000

# Create a non-privileged system user for security hardening
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy pruned production dependencies
COPY --from=deps /app/package.json ./package.json
COPY --from=deps /app/node_modules ./node_modules

# Copy compiled build output from builder stage
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

CMD ["node", "server.js"]

Key Optimizations in the Node.js Build

  • npm ci vs npm install: Ensures deterministic installations using the exact dependency tree defined in package-lock.json.
  • Non-Root Execution: Creating and switching to a dedicated nextjs system user prevents container breakout vulnerabilities from achieving root privileges on the host kernel.
  • Standalone Output: Leveraging Next.js standalone tracing copies exclusively the required node modules into the final bundle, bypassing the entire node_modules directory.

Production-Ready PHP-FPM and Nginx Multi-Stage Dockerfile

PHP applications (such as Laravel 11) require a dual-process architecture: PHP-FPM to execute application logic and Nginx to terminate HTTP traffic and serve static files. Packaging both inside a single container using multi-stage builds and a process manager like supervisord maintains clean orchestration boundaries.

# Stage 1: Build PHP vendor dependencies via Composer
FROM composer:2.6 AS vendor-builder
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install \
    --no-dev \
    --no-interaction \
    --no-plugins \
    --no-scripts \
    --prefer-dist \
    --optimize-autoloader

# Stage 2: Production PHP-FPM & Nginx Runtime
FROM php:8.3-fpm-alpine AS production

# Install system dependencies and PHP extensions
RUN apk add --no-cache \
    nginx \
    supervisor \
    curl \
    libpng-dev \
    libxml2-dev \
    zip \
    unzip \
    && docker-php-ext-install pdo_mysql bcmath gd opcache

# Configure PHP production settings
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"

WORKDIR /var/www/html

# Copy application source code
COPY . /var/www/html
# Inject optimized vendor directory from Stage 1
COPY --from=vendor-builder /app/vendor /var/www/html/vendor

# Set correct permissions for storage and cache directories
RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache

# Copy custom Nginx and Supervisor configurations
COPY docker/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

EXPOSE 80

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

Ensuring OPCache and Autoloader Optimization

In production PHP environments, omitting --no-dev and failing to enable OPCache degrades throughput by up to 300%. The multi-stage approach ensures that developer documentation, testing frameworks (PHPUnit), and local debugging tools never reach the production registry.


How BrickTry Accelerates & Powers This

Implementing secure, production-grade containerization across microservices requires balancing strict security policies with deployment velocity. This is where BrickTry transforms infrastructure management for engineering teams:

  • Interactive Browser Lab Sandbox (/lab): Test, debug, and iterate on complex multi-stage Dockerfiles instantly in a zero-setup, in-browser virtualized container environment without cluttering your local machine.
  • AI-Human Dev Pairing: BrickTry's autonomous AI agents scaffold optimized Dockerfiles, CI/CD pipeline scripts, and dependency locks, while dedicated senior full-stack engineering pods review your infrastructure for security vulnerabilities and performance bottlenecks.
  • Automated AST & Security Auditing: Every configuration is continuously scanned against compliance standards and container vulnerability databases before merging into your main branch.
  • Unified Importer: Seamlessly import existing monolithic GitHub repositories or legacy CodeCanyon scripts, automatically refactoring them into clean architecture patterns and containerizing them with multi-stage best practices.
  • 100% Source Code Ownership: Retain absolute control over your GitHub repositories, Docker configurations, and infrastructure-as-code scripts with zero vendor lock-in.

Build, Test, and Scale This on BrickTry

BrickTry pairs you with autonomous AI scaffolding supervised by dedicated senior full-stack software engineers in an interactive in-browser development sandbox. Test, build, and deploy production-grade software with 100% source code ownership and zero vendor lock-in.

Launch Interactive Requirement Builder →

❤️

Support BrickTry Platform & Engineering Development

Help us build, maintain, and advance our AI engineering platform. Every donation fuels open-source tooling, infrastructure, and continuous improvements.

$
Donor Details
Promote Your Brand / Link Wall

UPI / Credit & Debit Cards / Netbanking
Razorpay
Secure 256-bit encrypted checkout
View Leaderboard & Wall

Hey!

Welcome, Let's chat —
start a new conversation
below.

Recent conversations
See all

Hi ,We’d like to inform you that the Integ...

Abhishek A Agrawal • 1d ago

Abhishek A Agrawal

Back in a few hours