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.
Configure your Laravel Docker setup and generate production-ready files
Your Laravel Docker configuration files are ready for production deployment.
Laravel Boilerplate
The first Laravel SaaS boilerplate built for vibe coding. 200+ pre-built features, multiple payment processors, and optimized for Cursor.
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.
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.
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.
Based on current industry standards and Laravel 12 requirements, here are the essential considerations:
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.
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.
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.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 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 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 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 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.
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_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
Configure your IDE (Visual Studio Code, PHPStorm, etc.) to connect to the remote container for debugging:
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}
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 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 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 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.
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
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 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
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.
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.
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.
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
.
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.
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.
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
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.