Setting up a Local Environment for Laravel with Docker

Laravel is a powerful PHP framework for web application development. It has become a popular choice for developers due to its elegant syntax and the availability of various tools and packages that make development easier. Docker is a containerization platform that makes it easy to run and manage applications in containers. By combining Laravel and Docker, developers can create a local development environment that is easily maintainable, scalable, and portable.

In this article, we will show you how to set up a local environment for Laravel using Docker.

Prerequisites

Before getting started, you will need to install the following tools:

  • Docker: You can download the Docker Desktop for Mac or Windows from the official Docker website.
  • Laravel CLI: Laravel CLI can be installed by running the following command in your terminal: composer global require laravel/installer

Step 1: Create a Laravel Project

First, you will need to create a new Laravel project. You can do this by running the following command in your terminal:

laravel new myproject

This will create a new Laravel project in a directory named myproject.

Step 2: Create a Dockerfile

Next, you will need to create a Dockerfile in the root directory of your Laravel project. A Dockerfile is a script that contains all the commands necessary to build a Docker image. You can create the Dockerfile by running the following command in your terminal:

touch Dockerfile

Open the Dockerfile in a text editor and add the following content:

# Use an official PHP image as the base image
FROM php:7.4-apache

# Set the working directory to /app
WORKDIR /app

# Copy the contents of the current directory to the working directory
COPY . /app

# Install the necessary PHP extensions
RUN docker-php-ext-install mysqli pdo pdo_mysql

# Enable the Apache mod_rewrite module
RUN a2enmod rewrite

# Expose port 80 to the host
EXPOSE 80

# Set the entry point to Apache
ENTRYPOINT ["apache2-foreground"]

Step 3: Create a docker-compose.yml File

The next step is to create a docker-compose.yml file, which will define the services that make up your application. You can create the file by running the following command in your terminal:

touch docker-compose.yml

Open the docker-compose.yml file in a text editor and add the following content:

version: '3'
services:
  web:
    build: .
    ports:
      - "80:80"
  db:
    image: mysql:5.7
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: mydatabase
      MYSQL_USER: myuser
      MYSQL_PASSWORD: secret

Step 4: Build and Run the Docker Containers

With the Dockerfile and docker-compose.yml files in place,

docker-compose up

So this is that!