A standard Laravel Docker image can easily balloon to over 1GB if not managed correctly. This leads to slow deployments, high storage costs, and a larger attack surface. Multi-stage builds are the industry-standard solution, allowing you to separate your build-time dependencies (like Composer and NPM) from your final production runtime.
1. The Multi-Stage Architecture
The core idea is simple: Use a heavy image with all the tools needed to build your app, then copy only the compiled results into a tiny, high-performance runtime image like Alpine Linux.
The Three Stages of a Pro Pipeline:
- Stage 1: PHP Dependencies – Uses the official Composer image to install production-only vendors.
- Stage 2: Frontend Assets – Uses Node.js to compile your Vite/Tailwind assets and then discards the 1GB
node_modulesfolder. - Stage 3: Production Runtime – A clean PHP-FPM Alpine image that only contains your code and the specific extensions required.
2. Optimizing Build Speed with Layer Caching
At Bhagwati Team, we prioritize CI/CD efficiency. By copying composer.json and package.jsonbefore the rest of your code, Docker can cache your dependencies. If your code changes but your packages don’t, your build will finish in seconds instead of minutes.
Production-Ready Dockerfile Snippet
# Stage 1: Vendor build
FROM composer:2.7 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader
# Stage 2: Final Production Image
FROM php:8.3-fpm-alpine
WORKDIR /var/www/html
COPY --from=vendor /app/vendor ./vendor
COPY . .
RUN php artisan optimize 3. Alpine Linux: The Lightweight King
Switching from Debian-based images to Alpine Linux can reduce your base image size from 600MB to just 50MB. However, it uses musl libc instead of glibc, so ensuring your PHP extensions are compiled correctly is critical for stability.
Production Hardening Checklist:
- .dockerignore: Always exclude
.git,node_modules, and local.envfiles. - OPcache: Enable and tune OPcache in your production stage for a 2x performance boost.
- Non-Root User: Never run your PHP process as
root; use thewww-datauser for improved security.
Conclusion: Ship Faster, Ship Safer
Optimizing your Docker pipeline isn’t just about saving disk space—it’s about developer velocity. A lean image means faster uploads to your registry and faster deployments to your server. At Bhagwati Team, we build infrastructure that scales effortlessly while remaining incredibly cost-efficient.
"Your production image should be a refined artifact, not a junk drawer of build tools. If it isn't under 150MB, you're shipping more than just code—you're shipping technical debt."
