When building modern applications, containers simplify development by ensuring consistency across environments. With Docker, you can containerize your Laravel project, making setup faster, cleaner, and easier to scale.
🔹 Why Use Docker with Laravel?
- Consistency: Same environment for all developers.
- Isolation: Dependencies don’t pollute your system.
- Scalability: Run multiple services (PHP, MySQL, Redis) easily.
- Portability: Deploy anywhere Docker runs.
🔹 Step 1: Create a New Laravel Project
If you don’t have a Laravel project yet, create one:
composer create-project laravel/laravel laravel-docker
cd laravel-docker🔹 Step 2: Create a Dockerfile
Inside the project root, create a Dockerfile:
FROM php:8.2-fpm
# Install system dependencies
RUN apt-get update && apt-get install -y \
git curl libpng-dev libonig-dev libxml2-dev zip unzip
# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
# Install Composer
COPY --from=composer:2.6 /usr/bin/composer /usr/bin/composer
# Set working directory
WORKDIR /var/www
COPY . .
RUN composer install
CMD ["php-fpm"]🔹 Step 3: Create a docker-compose.yml
This file will define your services (Laravel, Nginx, MySQL):
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
container_name: laravel_app
working_dir: /var/www
volumes:
- .:/var/www
networks:
- laravel
webserver:
image: nginx:alpine
container_name: laravel_web
restart: unless-stopped
ports:
- "8080:80"
volumes:
- .:/var/www
- ./nginx.conf:/etc/nginx/conf.d/default.conf
networks:
- laravel
db:
image: mysql:8.0
container_name: laravel_db
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: laravel
MYSQL_USER: laravel
MYSQL_PASSWORD: secret
ports:
- "3306:3306"
networks:
- laravel
networks:
laravel:
driver: bridge🔹 Step 4: Create nginx.conf
server {
listen 80;
index index.php index.html;
root /var/www/public;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass app:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/public$fastcgi_script_name;
include fastcgi_params;
}
}🔹 Step 5: Build and Run Containers
Run the following commands:
# Build and start containers
docker-compose up -d --build
# Check running containers
docker ps
# Enter Laravel container
docker exec -it laravel_app bash
# Run migrations
php artisan migrateNow visit:
👉 https://localhost:8080
You should see your Laravel welcome page 🎉
🔹 Step 6: Useful Docker Commands
Stop containers:
docker-compose downRebuild containers:
docker-compose up -d --buildAccess database container:
docker exec -it laravel_db mysql -u laravel -p✅ Conclusion
By containerizing Laravel with Docker, you gain reliability, scalability, and portability. This setup allows you to extend easily—adding Redis, queues, or Elasticsearch later.