Laravel Dockerfile Generator

A secure, tiny image in one click

Generate production-ready Laravel Docker configurations with multi-stage builds, Nginx setup, Supervisor config, and health checks. Optimized for performance with Opcache and security best practices.

Laravel Dockerfile Generator

Configure your Laravel Docker setup and generate production-ready files

Configuration Generated Successfully!

Your Laravel Docker configuration files are ready for production deployment.

Dockerfile

                        
nginx.conf

                        
supervisor.conf

                        
healthcheck.sh

                        
Stack Toast - Laravel SaaS Boilerplate

Stack Toast

Laravel Boilerplate

Launch Your SaaS in Days, Not Months

The first Laravel SaaS boilerplate built for vibe coding. 200+ pre-built features, multiple payment processors, and optimized for Cursor.

Laravel 12 Ready
Cursor Optimized
Launch in Days
No Setup Hassles

Everything You Need

200+ Ready Features
Pre-built & tested
100+ AI Models
Integrated & ready
4 Payment Gateways
Stripe, Paddle, Lemon Squeezy, Coinbase
0 Headaches
Just start building

Complete Guide to Laravel Dockerfile and Supervisor Configuration

Docker has revolutionized the way we deploy and manage Laravel applications, providing consistency across development, staging, and production environments. This comprehensive guide covers everything you need to know about creating production-ready Laravel Dockerfiles, configuring Nginx for optimal performance, and setting up Supervisor for process management.

Getting Started with Your Laravel Docker Setup

Ready to create your production-ready Laravel Docker configuration? Use our Laravel Dockerfile Generator above to customize your setup based on your specific requirements. The tool generates optimized configurations for Dockerfile, Nginx, Supervisor, and health checks, ensuring your Laravel application runs efficiently in production.

Start by selecting the PHP extensions your application needs, configure queue workers and background services, and choose your preferred PHP and Node.js versions. The generator will create all necessary configuration files with security best practices and performance optimizations built-in.

Quick Start Steps:

  1. Configure your PHP extensions and versions
  2. Enable queue workers, Horizon, or Octane as needed
  3. Click "Generate Docker Configs" to create your files
  4. Copy the generated configurations to your project
  5. Build and deploy your Docker container

Understanding Laravel Dockerfile Architecture

A well-structured Laravel Dockerfile follows the multi-stage build pattern, which significantly reduces the final image size while maintaining all necessary functionality. The multi-stage approach separates the build process into distinct phases: dependency installation, asset compilation, and production runtime.

Laravel 12 Docker Best Practices

Based on current industry standards and Laravel 12 requirements, here are the essential considerations:

  • Use PHP 8.2+ as Laravel 12 requires this minimum version (PHP 8.4 recommended)
  • Implement multi-stage builds for optimal image size
  • Use Alpine Linux for smaller, more secure base images
  • Separate build dependencies from runtime dependencies
  • Optimize Composer autoloader for production
  • Use Node.js 20+ for modern frontend asset compilation

The first stage typically handles Node.js dependencies and frontend asset compilation. This stage uses the official Node.js Alpine image, which is lightweight and secure. The second stage manages PHP Composer dependencies, ensuring that only production dependencies are included in the final image. The third and final stage creates the production runtime environment with PHP-FPM, Nginx, and Supervisor.

Multi-Stage Build Benefits:

Size Optimization:
  • Excludes build tools from final image
  • Removes development dependencies
  • Eliminates unnecessary packages
Security Benefits:
  • Minimal attack surface
  • No development tools in production
  • Reduced vulnerability exposure

PHP Extensions and Performance Optimization

Laravel applications require specific PHP extensions to function properly. The most critical extensions include PDO MySQL for database connectivity, MBString for multibyte string handling, XML for data processing, and CType for character type checking. Additional extensions like GD for image manipulation, ZIP for file compression, and CURL for HTTP requests are commonly needed for modern Laravel applications.

Essential PHP Extensions for Laravel:

Core Extensions (Required):
  • PDO MySQL - Database connectivity
  • MBString - Multibyte string handling
  • XML - Data processing and parsing
  • CType - Character type checking
  • JSON - JSON data handling
  • BCMath - Arbitrary precision mathematics
  • Opcache - PHP bytecode caching
  • Tokenizer - PHP token parsing
  • OpenSSL - Cryptographic functions
  • PDO - Database abstraction layer
Optional Extensions:
  • GD - Image manipulation
  • ZIP - File compression
  • CURL - HTTP requests
  • Redis - Caching and queues
  • Imagick - Advanced image processing
  • Intl - Internationalization
  • EXIF - Image metadata
  • Sodium - Modern cryptography
  • PCNTL - Process control
  • Memcached - Memory caching
  • MongoDB - NoSQL database

Performance optimization in Docker containers involves several key strategies. Opcache configuration is crucial for production environments, as it caches compiled PHP bytecode in memory, significantly reducing execution time. The recommended Opcache settings include enabling the cache, allocating sufficient memory (typically 256MB), and configuring appropriate revalidation frequencies.

Opcache Configuration Best Practices:

opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.validate_timestamps=0

These settings optimize memory usage, file caching, and performance for production Laravel applications.

Nginx Configuration for Laravel

Nginx serves as the web server and reverse proxy for Laravel applications in Docker containers. A properly configured Nginx setup includes optimized worker processes, efficient connection handling, and comprehensive security headers. The configuration should handle static file serving, PHP-FPM proxying, and implement proper caching strategies.

Security considerations in Nginx configuration include hiding server tokens, implementing security headers like X-Frame-Options and X-Content-Type-Options, and denying access to sensitive directories like storage and bootstrap/cache. Performance optimizations include enabling gzip compression, setting appropriate buffer sizes, and configuring static file caching with proper expiration headers.

Supervisor Process Management

Supervisor is essential for managing multiple processes within a single Docker container. It ensures that critical services like Nginx, PHP-FPM, and Laravel queue workers remain running and automatically restart if they fail. Supervisor configuration includes process definitions, restart policies, logging settings, and user permissions.

Laravel queue workers are particularly important for background job processing. Supervisor can manage multiple queue worker processes, each handling different queue types or priorities. The configuration includes process naming, restart policies, and resource limits to prevent memory leaks and ensure optimal performance.

Laravel Horizon Integration

Laravel Horizon provides a beautiful dashboard and code-driven configuration for Redis queues. When enabled in Docker containers, Horizon manages queue workers automatically, provides real-time monitoring, and handles job balancing across multiple workers. Supervisor configuration for Horizon includes proper user permissions, logging, and graceful shutdown procedures.

Horizon's configuration in Docker environments requires careful attention to Redis connectivity, worker scaling, and memory management. The Supervisor configuration ensures Horizon starts automatically with the container and restarts gracefully during deployments.

Laravel Octane for High Performance

Laravel Octane dramatically improves application performance by keeping the application in memory between requests. When using Octane with Swoole or RoadRunner, the application bootstrap process occurs only once, eliminating the overhead of loading the framework for each request. This results in significantly faster response times and reduced memory usage.

Octane configuration in Docker requires special considerations for process management, memory allocation, and graceful shutdowns. Supervisor manages the Octane process, ensuring it starts with the container and handles restarts appropriately. The configuration includes proper user permissions, logging, and integration with the existing Nginx setup.

Debugging Laravel Applications with Xdebug

Xdebug is essential for debugging Laravel applications in Docker environments. It provides step-by-step debugging, profiling, and code coverage analysis, making it easier to identify and resolve issues during development.

Xdebug Configuration for Development

Environment Variables
XDEBUG_ENABLED=true
XDEBUG_MODE=develop,coverage,debug,profile
XDEBUG_HOST=host.docker.internal
XDEBUG_IDE_KEY=DOCKER
XDEBUG_LOG=/dev/stdout
XDEBUG_LOG_LEVEL=0
IDE Configuration

Configure your IDE (Visual Studio Code, PHPStorm, etc.) to connect to the remote container for debugging:

  • Set breakpoints in your Laravel code
  • Configure remote debugging connection
  • Use the XDEBUG_IDE_KEY for connection
  • Enable step-by-step debugging
Docker Compose Integration

Include Xdebug in your development Docker Compose configuration:

php-fpm:
  build:
    context: .
    dockerfile: ./docker/php-fpm/Dockerfile
    target: development
    args:
      XDEBUG_ENABLED: ${XDEBUG_ENABLED:-true}
      XDEBUG_MODE: develop,coverage,debug,profile
      XDEBUG_HOST: ${XDEBUG_HOST:-host.docker.internal}

Health Checks and Monitoring

Comprehensive health checks are essential for production Docker deployments. A well-designed health check script verifies that all critical services are running, the application is responding to requests, database connections are functional, and file permissions are correct. The health check should be lightweight, fast, and provide clear error messages for troubleshooting.

Docker's built-in health check feature integrates with orchestration platforms like Docker Swarm and Kubernetes, enabling automatic container replacement when health checks fail. The health check script should test multiple aspects of the application, including HTTP endpoints, database connectivity, and file system permissions.

Security Best Practices

Security in Laravel Docker deployments involves multiple layers of protection. Container security starts with using minimal base images, running processes as non-root users, and implementing proper file permissions. The application layer requires secure environment variable handling, proper secret management, and regular security updates.

Network security includes configuring proper firewall rules, using HTTPS in production, and implementing security headers. The Nginx configuration should include rate limiting, request size limits, and protection against common web vulnerabilities. Regular security audits and dependency updates are essential for maintaining a secure deployment.

Performance Optimization Strategies

Performance optimization in Laravel Docker containers involves multiple strategies working together. Image optimization includes using Alpine Linux base images, implementing multi-stage builds, and removing unnecessary packages. Runtime optimization involves proper PHP-FPM configuration, Opcache tuning, and efficient static file serving.

Database optimization includes connection pooling, query caching, and proper indexing. Application-level optimizations involve route caching, configuration caching, and view compilation. Monitoring and profiling tools help identify bottlenecks and measure the effectiveness of optimization efforts.

Docker Compose Configuration

Docker Compose is a powerful tool for managing multi-container environments, particularly in development due to its simplicity. With Docker Compose, you can define and connect all necessary services for Laravel, such as PHP, Nginx, and databases, in a single configuration file. This setup ensures consistency across development, testing, and production environments, streamlining onboarding and reducing discrepancies between local and server setups.

Why Use Docker Compose for Laravel?

Development Benefits:
  • Simplified multi-container management
  • Consistent environment across team members
  • Easy service orchestration and networking
  • Volume mounting for live code updates
  • Integrated debugging with Xdebug
Production Considerations:
  • Great for simple deployments
  • Consider Docker Swarm for advanced scaling
  • Kubernetes for complex orchestration
  • Health checks for service reliability
  • Optimized for performance and security

Essential Docker Compose Services

Application Service

The main Laravel application container that handles PHP processing and serves your application logic.

app:
  build:
    context: .
    dockerfile: Dockerfile
  image: your-laravel-app
  container_name: laravel-app
  ports:
    - "8000:8000"
  volumes:
    - .:/var/www/html
  networks:
    - app-network
Nginx Service

Web server that handles HTTP requests and serves static files while proxying PHP requests to the application container.

nginx:
  image: nginx:alpine
  container_name: nginx-container
  ports:
    - "80:80"
  volumes:
    - ./nginx/conf.d:/etc/nginx/conf.d
    - ./public:/var/www/html/public
  depends_on:
    - app
  networks:
    - app-network
Database Service

Database container (MySQL, PostgreSQL, etc.) that stores your application data with proper initialization and persistence.

mysql:
  image: mysql:8.0
  container_name: mysql-container
  environment:
    MYSQL_ROOT_PASSWORD: root_password
    MYSQL_DATABASE: laravel_db
    MYSQL_USER: laravel_user
    MYSQL_PASSWORD: laravel_password
  volumes:
    - mysql_data:/var/lib/mysql
  networks:
    - app-network

Development vs Production Configurations

Understanding the differences between development and production Docker configurations is crucial for creating effective Laravel applications. Each environment has specific requirements and optimizations that must be carefully considered.

Development Environment Features

Development Tools:
  • Xdebug for debugging and profiling
  • Volume mounts for live code updates
  • Development PHP configuration
  • Workspace container for CLI tasks
  • Hot reloading for frontend assets
Development Benefits:
  • Real-time code changes without rebuilds
  • Integrated debugging capabilities
  • Simplified development workflow
  • Consistent team environments
  • Easy access to logs and debugging

Production Environment Optimizations

Production Features:
  • Multi-stage builds for minimal image size
  • Production PHP configuration
  • Optimized Opcache settings
  • Health checks for service monitoring
  • Security-hardened configurations
Production Benefits:
  • Smaller image sizes for faster deployments
  • Enhanced security and performance
  • Automated health monitoring
  • Optimized for scalability
  • Production-ready configurations

Deployment and CI/CD Integration

Modern deployment strategies for Laravel Docker applications involve continuous integration and continuous deployment pipelines. The Dockerfile should be optimized for build caching, with frequently changing files copied last to maximize cache utilization. Build arguments and multi-platform builds enable deployment across different architectures.

CI/CD pipelines should include automated testing, security scanning, and performance testing. Deployment strategies like blue-green deployments and rolling updates minimize downtime and reduce deployment risks. Environment-specific configurations ensure proper behavior across development, staging, and production environments.

Troubleshooting Common Issues

Common issues in Laravel Docker deployments include permission problems, memory limitations, and service startup failures. Permission issues often arise from file ownership conflicts between the host system and container. Proper user creation and file permission management prevent these problems.

Common Docker Issues & Solutions

Port Conflicts

If you face issues starting your Docker containers, port conflicts are a common culprit. This happens when the ports defined in your docker-compose.yml file are already in use by other applications on your system.

Solution: Identify the process using the port with commands like netstat -tulnp (on Linux/macOS) or change the ports in your docker-compose.yml. For example, change the host port mapping like 8080:80 to 8081:80.

Database Connection Errors

Laravel might fail to connect to the database container. This can stem from incorrect database credentials, network issues, or the database server not being ready yet.

Solution: Verify credentials in your .env file and docker-compose.yml, ensure database service is healthy, check network connectivity, and add dependencies to ensure the Laravel app starts after the database is ready.

Permissions Issues

File permission problems inside the Docker container can prevent Laravel from writing to storage or cache directories.

Solution: Adjust file permissions within the container using commands like RUN chown -R www-data:www-data storage bootstrap/cache to give the web server user ownership of these directories.

Cache Problems

Cached configurations or routes can sometimes cause unexpected behavior after changes.

Solution: Clear Laravel's caches by executing these commands inside your running application container:

php artisan cache:clear
php artisan route:clear
php artisan config:clear
php artisan view:clear
Application Key Not Set

Laravel requires an application key for security. If it's not set, you might encounter errors.

Solution: Generate and set the application key by running php artisan key:generate in your container and ensure the APP_KEY environment variable is set in your .env file.

Memory issues can occur when containers exceed allocated resources or when applications have memory leaks. Proper resource limits, monitoring, and garbage collection tuning help prevent these problems. Service startup failures often result from configuration errors, missing dependencies, or network connectivity issues.

Monitoring and Logging

Effective monitoring and logging are crucial for maintaining healthy Laravel Docker deployments. Centralized logging enables tracking application behavior, identifying errors, and analyzing performance patterns. Log aggregation tools like ELK Stack or Fluentd collect logs from multiple containers and provide searchable interfaces.

Application Performance Monitoring (APM) tools provide insights into application behavior, database performance, and external service dependencies. Metrics collection includes system resources, application metrics, and business metrics. Alerting systems notify administrators of critical issues requiring immediate attention.

Scaling and Load Balancing

Scaling Laravel Docker applications involves horizontal scaling through multiple container instances and load balancing. Load balancers distribute incoming requests across multiple container instances, improving availability and performance. Session management and stateful application considerations are important for scaling decisions.

Database scaling strategies include read replicas, connection pooling, and caching layers. Queue scaling involves multiple worker processes and distributed queue systems. Auto-scaling based on metrics like CPU usage, memory consumption, and request rates ensures optimal resource utilization.

Frequently Asked Questions

What is the difference between a single-stage and multi-stage Dockerfile?

A single-stage Dockerfile includes all build dependencies in the final image, resulting in larger image sizes. Multi-stage Dockerfiles separate the build process from the runtime environment, creating smaller, more secure production images by excluding build tools and dependencies.

Why should I use Supervisor in my Laravel Docker container?

Supervisor manages multiple processes within a single container, ensuring that Nginx, PHP-FPM, and Laravel queue workers remain running. It provides automatic restarts, process monitoring, and centralized logging, making it essential for production deployments.

How do I optimize my Laravel Docker image size?

Use Alpine Linux base images, implement multi-stage builds, remove unnecessary packages, and leverage Docker layer caching. Copy frequently changing files last in the Dockerfile to maximize cache utilization and reduce build times.

What PHP extensions are essential for Laravel?

Essential extensions include PDO MySQL, MBString, XML, CType, JSON, BCMath, Opcache, Tokenizer, OpenSSL, and PDO. Optional but commonly used extensions include GD for image processing, ZIP for file compression, CURL for HTTP requests, and Redis for caching and queues.

How do I configure Opcache for production?

Enable Opcache, allocate sufficient memory (256MB+), set appropriate revalidation frequencies, and configure fast shutdown. Disable timestamp validation in production to maximize performance, but ensure proper deployment procedures to clear the cache when needed.

What are the benefits of using Laravel Octane?

Laravel Octane keeps the application in memory between requests, eliminating the bootstrap overhead. This results in significantly faster response times, reduced memory usage, and improved throughput, especially for high-traffic applications.

How do I handle file permissions in Docker containers?

Create a non-root user in the Dockerfile, set proper file ownership using COPY --chown, and ensure storage and cache directories are writable. Use consistent UIDs between host and container to avoid permission conflicts.

What security considerations should I keep in mind?

Use minimal base images, run processes as non-root users, implement security headers in Nginx, use HTTPS in production, regularly update dependencies, and implement proper secret management. Regular security audits and vulnerability scanning are essential.

How do I monitor my Laravel Docker application?

Implement health checks, use centralized logging, set up application performance monitoring, collect system metrics, and configure alerting. Tools like Prometheus, Grafana, and ELK Stack provide comprehensive monitoring solutions.

Can I use this Dockerfile for both development and production?

While the same Dockerfile can be used for both environments, it's recommended to have environment-specific configurations. Use build arguments, environment variables, and separate compose files to customize behavior for different environments.

What are the benefits of using Alpine Linux in Docker containers?

Alpine Linux provides a minimal, security-oriented Linux distribution that results in smaller Docker images (typically 5-10MB base image vs 100MB+ for Ubuntu). It includes a package manager (apk) and essential tools while maintaining security through its minimal attack surface and regular security updates.

How do I handle environment variables in Docker containers?

Use Docker's environment variable system with .env files, docker-compose environment sections, or runtime environment variables. Never hardcode sensitive data in Dockerfiles. Use secrets management for production deployments and ensure proper .env file handling in your Laravel application.

What's the difference between PHP-FPM and Laravel Octane?

PHP-FPM is the traditional process manager that handles each request independently, requiring full application bootstrap for each request. Laravel Octane keeps the application in memory between requests, dramatically improving performance but requiring careful memory management and state handling.

How do I optimize Docker build times for Laravel applications?

Use multi-stage builds, leverage Docker layer caching by copying package files before source code, use .dockerignore to exclude unnecessary files, and consider using BuildKit for parallel builds. Order Dockerfile instructions from least to most frequently changing.

What are the best practices for Laravel queue workers in Docker?

Use Supervisor to manage queue workers, implement proper restart policies, set memory limits to prevent memory leaks, use separate containers for different queue types, and implement graceful shutdown procedures. Consider using Laravel Horizon for advanced queue management.

How do I handle Laravel storage and file uploads in Docker?

Use Docker volumes for persistent storage, ensure proper file permissions with non-root users, consider using cloud storage services for scalability, and implement proper backup strategies. Use symbolic links for public storage when needed.

What's the recommended approach for database connections in Docker?

Use separate database containers or external database services, implement connection pooling, configure proper timeout settings, use environment variables for connection strings, and consider read replicas for scaling. Always use proper database credentials management.

How do I implement zero-downtime deployments with Docker?

Use blue-green deployments, implement health checks, use load balancers for traffic switching, implement graceful shutdowns, use database migrations carefully, and consider using orchestration tools like Docker Swarm or Kubernetes for advanced deployment strategies.

What are the key considerations for Laravel caching in Docker?

Use Redis or Memcached for distributed caching, implement proper cache invalidation strategies, configure cache drivers appropriately, use cache tags for complex invalidation, and consider using CDN for static asset caching. Monitor cache hit rates and performance.

Why use Docker for Laravel development?

Docker ensures consistent environments across development, staging, and production, eliminates "it works on my machine" problems, simplifies setup and deployment, provides isolation from system dependencies, and makes collaboration easier by standardizing the development environment.

How do I start and stop my Laravel Docker application?

Use docker-compose up -d to start all containers in detached mode, and docker-compose down to stop and remove containers. Access your application at http://localhost or http://localhost:8000 depending on your port configuration.

What's the difference between Docker and Laravel Homestead?

Docker is more flexible and cross-platform, allowing you to define custom environments and services. Homestead is simpler for local Laravel development but less portable and doesn't provide the same level of customization and production-like environment that Docker offers.

How do I configure environment variables in Docker?

Use Docker's environment variable system with .env files, docker-compose environment sections, or runtime environment variables. Never hardcode sensitive data in Dockerfiles. Use secrets management for production deployments and ensure proper .env file handling in your Laravel application.

What are the benefits of using Alpine Linux in Docker containers?

Alpine Linux provides a minimal, security-oriented Linux distribution that results in smaller Docker images (typically 5-10MB base image vs 100MB+ for Ubuntu). It includes a package manager (apk) and essential tools while maintaining security through its minimal attack surface and regular security updates.

What are the latest supported PHP and Node.js versions?

The generator supports PHP 8.2, 8.3, and 8.4 (latest), with PHP 8.4 being the recommended version for new projects. For Node.js, we support versions 20, 22, 23, and 24 (latest), with Node.js 24 being the recommended version for modern frontend asset compilation and build processes.

Why should I use Docker Compose for Laravel?

Docker Compose is a powerful tool for managing multi-container environments, particularly in development due to its simplicity. With Docker Compose, you can define and connect all necessary services for Laravel, such as PHP, Nginx, and databases, in a single configuration file. This setup ensures consistency across development, testing, and production environments, streamlining onboarding and reducing discrepancies between local and server setups.

How do I debug my Laravel application with Docker Compose?

To debug your Laravel application in a Docker environment, use Xdebug. In the development setup, Xdebug is installed in the php-fpm container to enable debugging. Ensure Xdebug is enabled in your compose.dev.yaml file by setting the environment variable XDEBUG_ENABLED=true and configuring your IDE (e.g., Visual Studio Code or PHPStorm) to connect to the remote container for debugging.

Can I use Docker Compose with databases other than PostgreSQL?

Yes, Docker Compose supports various database services for Laravel. While PostgreSQL is used in many examples, you can easily substitute MySQL, MariaDB, or even SQLite. Update the compose.*.yaml file to specify the required Docker image and adjust your .env file to reflect the new database configuration.

How can I persist data in development and production?

In both development and production, Docker volumes are used to persist data. For instance, in the compose.*.yaml file, the postgres-data-* volume stores PostgreSQL data, ensuring that data is retained even if the container restarts. You can also define named volumes for other services where data persistence is essential, such as Laravel storage directories.

What is the difference between development and production Docker configurations?

In a development environment, Docker configurations include tools that streamline coding and debugging, such as Xdebug for debugging, and volume mounts to enable real-time code updates without requiring image rebuilds. In production, the configuration is optimized for performance, security, and efficiency. This setup uses multi-stage builds to keep the image lightweight and includes only essential tools, packages, and libraries. It's recommended to use alpine-based images in production for smaller image sizes, enhancing deployment speed and security.