How to Set Up Laravel in Docker

Laravel is a PHP based web framework known for its clean and easy to use architecture which makes web development easier and more efficient. Setting up a Laravel application in Docker creates a consistent and isolated development environment. This setup not only facilitates development but also simplifies deployment and scaling. 

In this tutorial, we will walk you through a step-by-step procedure for setting up Laravel in Docker.

Setting Up Laravel in Docker: A Quick Guide

Docker is a powerful tool that allows the packaging of single or multiple applications into containers. In Docker, setting up Laravel creates an environment that prevents conflicts and streamlines the development of applications.

To set up Laravel in Docker, consider the below instructions with practical demonstration:

Step 1: Install Docker and Docker Compose

Docker is responsible for running individual containers, while Docker Compose lets us define and run multi-container Docker applications using a single YAML file. Therefore, to set up Laravel in Docker, it’s essential to install Docker on Ubuntu system.

Step 2: Set Up Your Laravel Project

After the installation, you can set up the new Laravel project or navigate to the existing project directory. For instance, download the sample project from GitHub named travellist-laravel-demo:

curl -L https://github.com/do-community/travellist-laravel-demo/archive/tutorial-1.0.1.zip -o travellist.zip
download the sample project from github

After downloading, extract the sample project with the unzip utility:

unzip travellist.zip
extract the sample project

Now, move all extracted files to the new project folder named travellist-demo:

mv travellist-laravel-demo-tutorial-1.0.1 travellist-demo

Let’s access the travellist-demo folder using the following command:

cd travellist-demo
access the demo folder

Step 3: Prepare the .env File

Laravel’s environment configurations are stored in the .env file. In this file, you can modify the database settings to your Docker service names and credentials. To configure the development environment, let’s copy the existing template:

cp .env.example .env

Now create a new .env file based on the existing template:

nano .env
create env file

Let’s copy the code below and paste it into the .env file:

APP_NAME=Travellist
APP_ENV=dev
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=travellist
DB_USERNAME=travellist_user
DB_PASSWORD=password

This step is crucial for connecting your Laravel application to the correct database container:

connecting laravel application to database container

After that, save and close the file.

Step 4: Create a Dockerfile

For Laravel, the Dockerfile sets up the PHP environment, installs dependencies, and sets up any necessary extensions. Let’s create it in the working directory:

nano Dockerfile

Now, copy the code below and paste it into the Dockerfile file:

FROM php:8.2-fpm
ARG user
ARG uid
RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev 
RUN apt clean && rm -rf /var/lib/apt/lists/*
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
    chown -R $user:$user /home/$user
WORKDIR /var/www
USER $user

Then, save and close the file:

create a docker file

Step 5:  Setting Up Nginx Configuration and Database Dump Files

Now, create a docker-compose/nginx folder in the project directory to store configuration files:

mkdir -p docker-compose/nginx

In this folder, create a .conf file to perform Nginx configuration. Let’s create the file named travellist.conf, which sets up Nginx to serve our application:

nano docker-compose/nginx/travellist.conf

Now, copy the Nginx configuration below and save it as a file named travellist.conf in the current directory:

server {

    listen 80;
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/public;
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        gzip_static on;
    }
}

After pasting the above code in the travellist.conf file, save, and close the file:

set up nginx configuration

Now, add a new folder named mysql for MySQL initialization files in the docker-compose directory:

mkdir docker-compose/mysql

Let’s open the init_db.sql file located in the docker-compose/mysql/ directory using the nano text editor for editing:

nano docker-compose/mysql/init_db.sql
mysql initialization

Now, add the following MySQL commands to the init_db.sql file. You can also add customized SQL statements to display on the webpage:

SELECT 'Ultahost Setting up Laravel in Docker' AS message;
specify mysql commands in initdb

After that, save and close the .sql file in the nano editor.

Step 6: Define Services in docker-compose.yml

The docker-compose.yml file specifies the Docker networks, services, volumes, and many more. For a Laravel application, you typically need services like PHP, Nginx or Apache, MySQL, or other services depending on your application’s needs. Let’s create the .yml file:

sudo nano docker-compose.yml

Now, add the definition of services, db, nginx, and networks to the docker-compose.yml file under the corresponding sections:

version: "3.7"
services:
  app:
    build:
      args:
        user: anees
        uid: 1000
      context: ./
      dockerfile: Dockerfile
    image: travellist
    container_name: travellist-app
    restart: unless-stopped
    working_dir: /var/www/
    volumes:
      - ./:/var/www
    networks:
      - travellist

  db:
    image: mysql:8.0
    container_name: travellist-db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USERNAME}
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - ./docker-compose/mysql:/docker-entrypoint-initdb.d
    networks:
      - travellist

  nginx:
    image: nginx:alpine
    container_name: travellist-nginx
    restart: unless-stopped
    ports:
      - 8000:80
    volumes:
      - ./:/var/www
      - ./docker-compose/nginx:/etc/nginx/conf.d/
    networks:
      - travellist

networks:
  travellist:
    driver: bridge
define services in docker compose

In the end, save and close the file. 

Step 7: Build and Run Your Containers

With the Dockerfile and docker-compose.yml in place, you can build your application’s Docker image and run the containers. This is done using the docker-compose up command, which will start and run your entire app:

sudo docker-compose up -d
run your containers

Step 8: Accessing Your Application

After everything is set up, you can access your Laravel application via the web browser at the specified port 8000 (configured in Step 3). Now, open the web browser and navigate to http://localhost:8000:

access laravel application

The output confirms that we have successfully set up a Laravel application in Docker.

Conclusion

Setting up Laravel in Docker involves several key steps to ensure a smooth development environment. First, you need to create a Dockerfile that defines the PHP environment suitable for Laravel, including necessary extensions and Composer. Next, a docker-compose.yml file is essential to define services such as Nginx, MySQL, and PHPMyAdmin, which are common in Laravel applications. 

Once the configuration files are ready, you can build and run your containers using Docker Compose, which will set up the entire environment. Afterward, you can access your Laravel application through the specified ports and manage your database. 

We hope this guide has helped you easily set up Laravel on Docker. You can integrate Docker with Ultahost’s best Linux VPS server for an optimized Laravel environment. Enjoy super-fast SSD NVMe speeds with no delays, making sure your Laravel app runs smoothly on Docker.

FAQ

What are the benefits of setting up Laravel in Docker?
What are the prerequisites for setting up Docker Laravel?
How do I prepare the Laravel .env file for Docker?
What is the purpose of a Dockerfile in this setup?
What does Nginx configuration do in this context?
What is the role of docker-compose.yml?
How do I build and run the Docker containers?

Related Post

How to Install Docker on Debian

Docker is a powerful containerization platform that all...

How to Redirect non-www to www URLs

Redirecting non-www to www URLs is a common task for sy...

Importing and Exporting Products in CSV Using

Starting an online store can be complex due to the time...

How to Create Custom Error Pages in cPanel

Ever encountered a generic messages page while browsing...

How to Check and Manage Logs on Docker Compo

Managing logs in Docker Compose is essential for develo...

How to connect MySQL Database with PHP Websit

Integrating a MySQL database with a PHP website in web ...

Leave a Comment