In today’s fast-paced development environment, setting up a reliable and efficient development environment is crucial for any Laravel project.
Docker has revolutionized the way we build, ship, and run applications by providing a standardized platform for containerization. In this comprehensive guide, we’ll walk you through the process of building a robust Laravel development environment using Docker.
From setting up persistent storage for both Laravel application data and MySQL databases to configuring communication between containers, we’ll cover everything you need to know to streamline your Laravel development workflow.
Whether you’re a seasoned developer looking to optimize your workflow or a newcomer eager to dive into Laravel development, this guide will equip you with the tools and knowledge to build and deploy Laravel applications with ease. Let’s dive in!
Dockerfile for Laravel:
# Use the official PHP image as base
FROM php:8.2-apache
# Update package lists and install dependencies
RUN apt-get update && \
apt-get install -y libpng-dev libjpeg-dev libfreetype6-dev zip unzip && \
docker-php-ext-configure gd --with-freetype --with-jpeg && \
docker-php-ext-install gd pdo_mysql && \
a2enmod rewrite
# Set working directory
WORKDIR /var/www/html
# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Install the latest version of Laravel
RUN composer create-project --prefer-dist laravel/laravel .
# Set permissions
RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache
# Expose port 80 to the outside world
EXPOSE 80
# Define a volume for Laravel storage
VOLUME /var/www/html/storage
Dockerfile for MySQL:
# Use the official MySQL image as base
FROM mysql:latest
# Set environment variables for MySQL configuration
ENV MYSQL_ROOT_PASSWORD=root_password
ENV MYSQL_DATABASE=laravel_db
ENV MYSQL_USER=laravel_user
ENV MYSQL_PASSWORD=laravel_password
# Expose the default MySQL port
EXPOSE 3306
# Define a volume for MySQL data
VOLUME /var/lib/mysql
Create Docker Network:
docker network create laravel_network
Build and Run Commands:
For Laravel
docker build -t laravel_app .
docker run -d --name laravel_container -p 8000:80 --network laravel_network -v laravel_storage:/var/www/html/storage laravel_app
For MySql
docker build -t mysql_laravel .
docker run -d --name mysql_container -p 3306:3306 --network laravel_network -v mysql_data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root_password -e MYSQL_DATABASE=laravel_db -e MYSQL_USER=laravel_user -e MYSQL_PASSWORD=laravel_password mysql_laravel
With these Dockerfiles and commands, you’ll have both the Laravel and MySQL containers set up with persistent storage and connected to the same Docker network for communication.