Get started with 33% off your first certification using code: 33OFFNEW

How To Set Up Laravel, Nginx, and MySQL With Docker Compose on Ubuntu 20.04

2 min read
Published on 6th October 2023
How To Set Up Laravel, Nginx, and MySQL With Docker Compose on Ubuntu 20.04

Running a Laravel application with Nginx and MySQL typically involves multiple steps of installation and configuration. Utilizing Docker Compose alleviates these pains by automating the setup, allowing you to bundle all components into isolated containers. This article walks you through the process of setting up a Laravel project with Nginx and MySQL using Docker Compose on Ubuntu 20.04.

Prerequisites

  • Ubuntu 20.04 installed on your machine.
  • Docker and Docker Compose installed. If not, refer to the official Docker installation guide.
  • Basic understanding of Docker, Laravel, Nginx, and MySQL.

Step 1: Setup Your Laravel Project

  1. Create a new Laravel project, or navigate to your existing project directory.
laravel new myproject
cd myproject

Step 2: Create Docker Compose File

  1. In the project root, create a docker-compose.yml file.
  2. Define the services - nginx, mysql, and app (Laravel).
version: '3'
services:
    nginx:
    image: nginx:stable-alpine
    ...
    mysql:
    image: mysql:5.7
    ...
    app:
    image: php:7.4-fpm

Step 3: Configure Nginx

  1. Create an nginx folder in the project root.
  2. Inside the nginx folder, create a default.conf file to configure the Nginx server block.
server {
    listen 80;
    index index.php index.html;
    root /var/www/html/public;
    ...
}

Step 4: Build and Run Containers

  1. Run the following command in the project root to start the containers:

docker-compose up -d

Step 5: Configure the Laravel Application

  1. Set up the environment variables in your .env file to connect to the MySQL container.

    envCopy code

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
...
  1. Run the migrations to initialize the database.

docker-compose exec app php artisan migrate

Summary

Setting up a Laravel, Nginx, and MySQL development environment on Ubuntu 20.04 with Docker Compose streamlines your development process, offering a consistent and replicable environment. Follow the steps above to effortlessly spin up or tear down your development setup, allowing you to focus more on coding and less on configuration.