Laravel Docker Multi-Stage Build with Vite: From 1.2GB to 150MB

Avatar
M

Maksudur Rahman

Software Engineerβ€’
0Views
5mRead
0Reactions

TL;DR: Combining Node.js asset compilation and PHP-FPM into a single container bloats production images past 1.2 GB and stalls CI pipelines. A 3-stage Docker build isolates Vite compilation, installs Composer dependencies with isolated layer caching, and packages only runtime artifacts into a lean Alpine image under 150 MB.

The Bottleneck: Bloated Images and Slow CI Deploys

A standard single-stage Laravel Docker build copies the entire repository, installs Node, runs npm run build, and leaves behind hundreds of megabytes of discarded build tooling:

  • Node.js binaries and the bloated node_modules/ folder stay trapped in the final layer.

  • Vite recompiles every asset on every pipeline run, regardless of whether frontend files changed.

  • Unnecessary test suites, Git history, and development utilities inflate the attack surface.

The solution is a Docker multi-stage build:

  1. Stage 1 (node-builder): Compiles CSS/JS bundles with Vite and outputs them to public/build.

  2. Stage 2 (php-builder): Resolves Composer dependencies without dev packages or discovery errors.

  3. Stage 3 (runtime): A minimal php:8.3-fpm-alpine base image containing only the application code, compiled static assets, and optimized production vendor files.

flowchart TD
    subgraph Stage1 ["Stage 1: node-builder (Node 20 Alpine)"]
        A[package.json & lockfile] --> B[npm ci]
        C[resources/ & configs] --> D[npm run build]
        B --> D
        D --> E["Compiled Assets (public/build)"]
    end

    subgraph Stage2 ["Stage 2: php-builder (Composer 2.7)"]
        F[composer.json & lockfile] --> G["composer install --no-dev --no-scripts"]
        H[Application Source Code] --> I["composer dump-autoload --optimize"]
        G --> I
        I --> J["Optimized vendor/"]
    end

    subgraph Stage3 ["Stage 3: Production Runtime (PHP 8.3 FPM Alpine)"]
        K[Base System Libs & Extensions] --> L[Copy vendor/ from Stage 2]
        H --> L
        E --> L
        L --> M["Final Production Image (~150 MB)"]
    end

Step 1: Configure a Strict .dockerignore

Place a .dockerignore file at your repository root. Every file ignored here prevents cache invalidation and keeps local test artifacts out of the build context:

# .dockerignore
.git
.github
node_modules
vendor
.env*
Dockerfile
docker-compose*.yml
tests
storage/*.key
storage/logs/*.log
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
README.md
.phpunit.cache
.idea
.vscode

Step 2: Construct the Production Multi-Stage Dockerfile

Create your multi-stage configuration at docker/Dockerfile.

# =============================================================
# Stage 1: Frontend Asset Compilation (Vite + Tailwind)
# =============================================================
FROM node:20-alpine AS node-builder
WORKDIR /app

# Cache dependency layer: install ALL dependencies (Vite is in devDependencies)
COPY package.json package-lock.json ./
RUN npm ci

# Copy configurations and frontend source files
COPY vite.config.* tsconfig*.json tailwind.config.* postcss.config.* ./
COPY resources/ ./resources/
COPY public/ ./public/

# Compile production bundles into public/build
RUN npm run build

# =============================================================
# Stage 2: PHP Dependency Installation (Composer)
# =============================================================
FROM composer:2.7 AS php-builder
WORKDIR /app

COPY composer.json composer.lock ./

# Install vendor dependencies without executing artisan discovery scripts
RUN composer install \
    --no-dev \
    --no-interaction \
    --no-scripts \
    --no-autoloader \
    --prefer-dist

# Copy the entire Laravel application
COPY . .

# Generate the classmap autoloader now that app/ and routes/ exist
RUN composer dump-autoload --optimize --no-dev

# =============================================================
# Stage 3: Lean Production Runtime (Alpine PHP-FPM)
# =============================================================
FROM php:8.3-fpm-alpine AS runtime
WORKDIR /var/www/html

# Install essential system libraries & PHP extensions
RUN apk add --no-cache \
    libpng-dev \
    libjpeg-turbo-dev \
    freetype-dev \
    zip \
    unzip \
    icu-dev \
    libzip-dev && \
    docker-php-ext-configure gd --with-freetype --with-jpeg && \
    docker-php-ext-install -j$(nproc) gd pdo pdo_mysql zip opcache bcmath

# Copy vendor dependencies and application code from php-builder
COPY --from=php-builder /app ./

# Copy compiled static assets from node-builder
COPY --from=node-builder /app/public/build ./public/build

# Ensure framework storage directories exist and assign secure permissions
RUN mkdir -p storage/framework/cache/data \
             storage/framework/sessions \
             storage/framework/views \
             storage/logs \
             bootstrap/cache && \
    chown -R www-data:www-data storage bootstrap/cache && \
    chmod -R 775 storage bootstrap/cache

# Production default configurations
ENV APP_ENV=production \
    APP_DEBUG=false \
    LOG_CHANNEL=stderr

EXPOSE 9000
CMD ["php-fpm"]

Why This Sequence Works

  • DevDependencies included in Stage 1: Vite and PostCSS compile cleanly without missing binaries.

  • --no-scripts in Stage 2: Prevents Composer from failing on @php artisan package:discover when artisan is not yet copied.

  • Guaranteed storage paths in Stage 3: Creating nested cache and session folders before chown ensures zero permission errors during cold boot.

Step 3: Automate CI Caching with GitHub Actions

Save the following workflow as .github/workflows/docker.yml. It uses Docker Buildx with GitHub Actions native cache (type=gha) to avoid caching bottlenecks:

name: Build and Push Laravel Image

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

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

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

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

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: docker/Dockerfile
          push: ${{ github.event_name != 'pull_request' }}
          tags: ghcr.io/${{ github.repository }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

[!NOTE] Setting push: ${{ github.event_name != 'pull_request' }} prevents unfinished pull requests from accidentally overwriting your production :latest registry image.

Step 4: Verify Image Size and Container Health

1. Build and Inspect Image Footprint Locally

docker build -f docker/Dockerfile -t laravel-app:test .
docker images laravel-app:test

Expected image footprint: ~145 MB to 160 MB (down from 1.2+ GB).

2. Verify PHP-FPM Configuration and Artisan Health

Because PHP-FPM listens on FastCGI instead of standard HTTP, test container status using the CLI:

# Check loaded extensions
docker run --rm laravel-app:test php -m

# Inspect application status
docker run --rm laravel-app:test php artisan about

3. Verify Compiled Vite Assets

Verify that Vite's manifest file was generated correctly:

docker run --rm laravel-app:test ls -la public/build

Benchmark: Single-Stage vs. Multi-Stage Build

Metric

Single-Stage Dockerfile

Multi-Stage (This Architecture)

Improvement

Final Image Size

1,280 MB

152 MB

⚑ 8.4x Smaller

Cold CI Build Time

12m 45s

4m 10s

πŸš€ 3x Faster

Warm CI Build (Vite Cached)

9m 30s

1m 15s

⚑ 7.6x Faster

Runtime Attack Surface

Node, npm, Git, dev packages

Alpine PHP-FPM & App Code only

Zero Node Binaries

4 Production Golden Rules for Dockerizing Laravel

  1. Never use --production in the Node Builder Stage: Vite, Tailwind, and PostCSS are defined in devDependencies. The Node container is discarded after compilation, so full installation is completely safe.

  2. Decouple Composer Autoloading: Always execute composer install --no-scripts --no-autoloader before copying application code. Generate the final autoloader (composer dump-autoload --optimize) only after the application tree is in place.

  3. Enforce type=gha in GitHub Actions: Avoid manual filesystem cache mounting (/tmp/.buildx-cache). Native GitHub Actions caching integrates with Buildx without disk growth issues.

  4. Pair PHP-FPM with an HTTP Ingress: Do not attempt to route browser traffic directly to port 9000. FastCGI requires a web server (Nginx, Traefik, Caddy) configured with fastcgi_pass.

Frequently Asked Questions (FAQ)

Why does npm ci need devDependencies in the Docker node-builder stage?

Vite, Tailwind CSS, and their framework plugins are installed under devDependencies in Laravel. The node-builder stage is discarded before the final runtime image is created, so installing them temporarily has zero impact on your production image size.

Can I browse PHP-FPM directly on port 9000 in a browser?

No. PHP-FPM communicates over binary FastCGI, not HTTP. You must pair it with an HTTP reverse proxy like Nginx, Traefik, or Caddy to translate HTTP requests into FastCGI calls.

Why run composer install with --no-scripts first?

Laravel defaults to running @php artisan package:discover during autoload dumping. Because the application source code has not yet been copied into the image at the dependency caching step, omitting scripts avoids fatal missing artisan errors.

How does GitHub Actions cache-from type=gha speed up Vite builds?

type=gha stores Buildx layer caches directly in GitHub's internal cache backend. When package.json and resources/ remain untouched, Buildx reuses the precompiled layers instantly instead of recompiling from scratch.

Connect with KoderSolution πŸš€

Master modern software engineering, scalable architectures, and advanced backend systems with KoderSolution:

  • 🌐 Official Website: Read more architectural deep-dives and tutorials on kodersolution.com

  • πŸ“Ί YouTube Channel: Subscribe to @kodersolution on YouTube for concise, animated system design breakdowns and shorts.

  • πŸ“± Facebook Page: Follow our official Facebook Page for daily development tips, architecture discussions, and community updates.

πŸ’¬ What's your setup? How does your team handle asset compilation in CI/CD pipelines? Are you using standalone multi-stage Docker builds or pre-compiling assets before container creation? Share your thoughts and join the discussion below!

Maksudur Rahman
M
Written byβ€’Software Engineer

Maksudur Rahman

Senior Developer Advocate & System Lead Moderator.

React to this article

Recommended Articles

View all articles