laravel-dockerize maintained by abolaradev
Laravel Docker Environment
A reusable Docker environment for Laravel applications, providing preconfigured services, development and production configurations, and automation scripts to simplify the Dockerization process.
Included Services
The Docker environment provides the following preconfigured services for Laravel applications.
Deployment-related services are defined in compose.yaml, while development-specific services and configurations are defined separately in compose.dev.yaml.
| Service | Description | Environment |
|---|---|---|
| Nginx | Web server and reverse proxy for HTTP requests. | All |
| PHP-FPM | Runs the Laravel application. | All |
| MySQL | Relational database for application data. | All |
| Redis | Handles caching, sessions, and queues. | All |
| Meilisearch | Provides full-text search functionality. | All |
| Queue Worker | Processes Laravel background jobs. | All |
| Scheduler | Executes scheduled Laravel tasks. | All |
| phpMyAdmin | Web-based MySQL database management interface. | Development |
| RedisInsight | Web-based Redis monitoring and management interface. | Development |
| Mailpit | Captures outgoing emails for development and testing. | Development |
Development-specific services are included when running Docker Compose with compose.dev.yaml.
Prerequisites
Make sure the following tools are installed:
- Docker Desktop or Docker Engine.
- Docker Compose V2 (version 2.22.0 or later for Watch support).
- Bash shell.
- OpenSSL.
Project Structure
.
├── docker/
│ ├── configs/
│ ├── scripts/
│ └── secrets/
├── Dockerfile
├── compose.yaml
├── compose.dev.yaml
├── .env
├── .env.docker.example
└── README.md
docker/configs/: Service configuration files.docker/scripts/: Automation and management scripts.docker/secrets/: Sensitive values used by Docker Secrets.Dockerfile: Multi-stage Docker build configuration.compose.yaml: Main deployment configuration.compose.dev.yaml: Development-specific configurations and services..env.docker.example: Example environment configuration.
Getting Started
1. Installation
Install the package via Composer:
composer require abolaradev/laravel-dockerize
Publish Docker Files
Run the following Artisan command to publish Docker files to the root directory of your Laravel application:
php artisan docker:install
2. Configure Environment
After placing the Docker environment files in your Laravel project root, copy the provided .env.docker.example file to create your .env file:
cp .env.docker.example .env
Set the application name by manually assigning a value to the APP_NAME variable in your .env file:
APP_NAME=YourApplicationName
Configure the database name using the application name. The DB_DATABASE variable should reference APP_NAME:
DB_DATABASE=${APP_NAME}
Configure the application timezone by updating the timezone option in config/app.php:
'timezone' => env('APP_TIMEZONE', 'UTC'),
You can then set your desired timezone through the APP_TIMEZONE variable in .env. If no value is provided, the application defaults to UTC.
Generate a new Laravel application encryption key:
php artisan key:generate
3. Generate Docker Secrets
This environment uses Docker Secrets to manage sensitive application and service credentials, such as database passwords, Redis passwords, and API keys.
Instead of passing sensitive values directly through environment variables, Docker Secrets mounts them as files inside the containers. This helps reduce the exposure of credentials through container environment inspection and keeps sensitive data separate from regular application configuration.
All secret files are stored in:
docker/secrets/
Secret Generator
The docker/scripts/secret-generator.sh script provides several options for creating and managing secret files:
| Option | Description |
|---|---|
--only-secret-file / -f |
Create secret files without generating random values. |
--secret-value / -v |
Specify a custom value for a secret file. |
--create-default-secret-files / -d |
Generate all predefined secret files at once. |
--help / -h |
Display available options and usage instructions. |
By default, the script generates secure random values using OpenSSL. Existing non-empty secret files are preserved.
Create Default Secret Files
To generate all predefined secret files in one step, run:
bash docker/scripts/secret-generator.sh -d
This creates the following files:
database_root_password.txtdatabase_password.txtredis_default_password.txtredis_password.txtmeilisearch_key.txt
Each secret is generated and stored separately under docker/secrets/.
These files are referenced in the secrets section of compose.yaml:
secrets:
database_root_password:
file: ./docker/secrets/database_root_password.txt
database_password:
file: ./docker/secrets/database_password.txt
redis_default_password:
file: ./docker/secrets/redis_default_password.txt
redis_password:
file: ./docker/secrets/redis_password.txt
meilisearch_key:
file: ./docker/secrets/meilisearch_key.txt
Note: The script requires Bash and OpenSSL. Never commit actual secret files to version control.
Using Docker Secrets in Laravel
To access Docker Secrets from Laravel configuration files, this project provides a custom helper function named docker_secret(), located at:
The helper reads the requested secret value from its corresponding mounted secret file.
Configure Laravel to Use Secrets
Replace the corresponding env() calls for sensitive values with docker_secret().
config/database.php — MySQL:
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => docker_secret('database_password'),
],
config/database.php — Redis:
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => docker_secret('redis_password'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => docker_secret('redis_password'),
]
config/scout.php — Meilisearch:
'meilisearch' => [
'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
'key' => docker_secret('meilisearch_key'),
],
3. Secret Naming
Pass the corresponding secret name as the argument to docker_secret().
Important: The argument must match the Docker Compose secret name and the corresponding secret file name without its .txt extension.
| Secret File | Helper Argument |
|---|---|
database_password.txt |
database_password |
redis_password.txt |
redis_password |
meilisearch_key.txt |
meilisearch_key |
This allows Laravel to retrieve sensitive values directly from Docker-mounted secret files instead of storing them in environment variables.
Running the Application
This environment supports two modes: Deployment and Production. Each mode uses a different Docker Compose configuration.
Deployment Environment
To build and start the application and all its services, including the deployment-related services, run:
docker compose -f compose.yaml -f compose.dev.yaml up -d --build
This command combines both Compose files and starts all defined services, including the development tools and deployment-related services.
Viewing Service Ports
To see which ports are exposed and bound to the host machine, run:
bash docker/scripts/ports.sh
Example output:
SERVICE | LOCAL ADDRESS
----------------------------------------------------------
database | http://127.0.0.1:3307
mailpit | http://127.0.0.1:1025
mailpit | http://127.0.0.1:8025
phpmyadmin | http://127.0.0.1:8080
redis-insight | http://127.0.0.1:5540
webserver | http://127.0.0.1:8000
Viewing Service Logs
To follow the logs of individual services, use:
Queue Worker:
docker compose logs -f queue
Scheduler:
docker compose logs -f scheduler
Docker Compose Watch
Docker Compose Watch monitors local project files and automatically synchronizes changes or rebuilds services according to the configured watch rules.
In this project, Watch is configured for the app, queue, and scheduler services.
To start these services with Watch enabled, run:
docker compose -f compose.yaml -f compose.dev.yaml up --watch app queue scheduler
The configured behavior is as follows:
- app: Synchronizes application files and rebuilds when dependency files change.
- queue: Synchronizes changes in job classes and restarts the service.
- scheduler: Synchronizes changes in
routes/console.phpand restarts the service.
OPcache Configuration
For development, the following settings are enabled in docker/configs/php.ini:
opcache.validate_timestamps=1
opcache.revalidate_freq=0
These settings ensure that OPcache checks PHP file modification timestamps on every request (validate_timestamps=1) and immediately detects changes without waiting for a revalidation interval (revalidate_freq=0).
This allows PHP code changes to take effect without manually restarting the PHP-FPM container.
Note: For production, timestamp validation is disabled (opcache.validate_timestamps=0) to improve performance. In this mode, PHP-FPM must be restarted or OPcache reset for code changes to take effect.
Running the Frontend Development Server
Start the Vite development server in your local project directory:
npm run dev
Once all services are running, the Laravel application will be accessible at:
Production Environment
Building and Starting Services
To build the application images and start all production services in the background, run:
docker compose up -d --build
Configuring Persistent Public Files
For production, configure the app and webserver services in compose.yaml as follows:
App service:
services:
app:
build:
context: .
target: app
restart: unless-stopped
volumes:
# Production:
- app_public:${WORKING_DIRECTORY}/public
Nginx service:
# Nginx web server and reverse proxy
webserver:
image: nginx:1.31.8
restart: unless-stopped
volumes:
- ./docker/configs/nginx.conf:/etc/nginx/conf.d/default.conf
# Production:
- app_public:${WORKING_DIRECTORY}/public:ro
The app_public named volume is shared between the application and Nginx containers. This allows Nginx to serve Laravel's public files while mounting the volume as read-only (ro) to prevent unintended modifications.
Important: Initial Volume Population
When Docker creates a new empty named volume and mounts it to a directory that already contains files in the container image, Docker automatically copies the existing directory contents into the volume.
Therefore, make sure the application image contains all required public files and compiled frontend assets before the volume is mounted for the first time.
Important: Subsequent Deployments
Named volumes persist independently of container lifecycles. When an existing app_public volume is mounted again, its contents are preserved and are not automatically replaced with files from a newly built application image.
As a result, rebuilding or recreating the application containers alone does not update the public files stored in the existing volume.
Whenever deploying a new application version, make sure the updated public directory and compiled assets are explicitly synchronized into the existing app_public volume.
This ensures that Nginx always serves the public files corresponding to the deployed application version.
OPcache Configuration
For production, update docker/configs/php.ini and enable the following setting:
; Production: disable timestamp validation
opcache.validate_timestamps=0
Disabling timestamp validation prevents OPcache from checking PHP file modification times on every request. This reduces filesystem checks and improves performance in production.
Important: Since PHP file changes are no longer detected automatically, rebuild and redeploy the application or reset OPcache whenever deploying new PHP code.
Rotating Passwords
You may need to change the initial credentials configured for MySQL and Redis for security or maintenance purposes.
1. Generate New Secret Values
Use the secret generator script to create new secret files for the desired credentials:
bash docker/scripts/secret-generator.sh database_password redis_password
This generates new values for the specified secret files.
Important: Updating a secret file does not automatically change the password of the corresponding MySQL or Redis user.
This is because the official MySQL image uses MYSQL_PASSWORD_FILE only during the initial database setup. Changing the secret file afterward does not update the password of an existing MySQL user. Similarly, Redis stores user credentials in its ACL configuration, which must be explicitly updated and saved.
2. Apply the New Credentials
To synchronize the new secret values with the actual user credentials, dedicated password rotation scripts are mounted into their respective containers through Docker Compose volumes.
These scripts are mounted rather than copied into the Docker images so they can be maintained and updated independently of the images, without requiring an image rebuild. They also execute inside the containers, giving them access to the mounted secret files and the local database or Redis instance.
MySQL:
To update the MySQL application user's password, run:
docker compose exec database /usr/local/bin/rotate-mysql-password.sh
Redis:
To update the Redis application user's password, run:
docker compose exec redis /usr/local/bin/rotate-redis-password.sh
Each script reads the updated secret value and applies it to the corresponding user inside the service. This ensures that the credentials stored in the secret files and the actual service authentication settings remain synchronized.
3. Recreate Services
After successfully rotating the passwords, recreate the services so that the containers are restarted with the updated secret files.
Deployment Environment:
docker compose -f compose.yaml -f compose.dev.yaml up -d --force-recreate
Production Environment:
docker compose up -d --force-recreate
Important: After rotating the passwords, ensure that the Laravel application and any other dependent services use the updated credentials. Verify connectivity after completing the rotation.
If you find this package useful, please don't forget to give it a ⭐ on GitHub. ❤️
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy for information on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.