How to run Laravel in Docker

Last update: 04-25-2024

Welcome to this step-by-step guide on setting up a Laravel development environment using Docker. instead of the hassles of traditional software installations, Docker offers a convenient and efficient way to manage your development setup. By containerizing the environment, Docker ensures that you can get up and running with Laravel on any operating system where Docker is available. This approach not only simplifies the initial setup but also maintains consistency across different machines and team members.

Initial Setup

To begin, create a new folder on your host machine. I'll refer to it as your-app but you can use any name you want.

Place the following files in the 'your-app' folder:

Dockerfile:

FROM php:8.3.6
WORKDIR /laravel-app
RUN apt update && apt install -y wget git unzip
RUN wget https://getcomposer.org/download/2.7.3/composer.phar -O /usr/local/bin/composer && chmod +x /usr/local/bin/composer
ENTRYPOINT ["tail", "-f", "/dev/null"]

Dockerfile Explanation:

docker-compose.yml:

version: '3.8'
services:
  php:
    build: .
    ports:
      - 8000:8000
    volumes:
      - .:/laravel-app

docker-compose.yml Explanation:

Starting the Docker container

To create the project:

  1. Open your terminal
  2. Navigate to the main folder (the one that contains the Dockerfile, docker-compose.yml and the example-app folder)
Then, run the following:
docker compose up --build

This will start the container and set the ground for the creation of the Laravel application.

Once the container is running

Attaching to the container

I recommend using Visual Studio Code for Laravel development. Visual Studio Code offers excellent integration with Docker conatiners - just make sure you have the "Dev Containers" extension installed.

code ../laravel-app

This will open a new VSCode window with your Laravel project open. Close the old VSCode window.

Creating the application

Using VSCode's built in terminal, create the Laravel application by running the following:

composer create-project laravel/laravel temp
mv temp/* ./ && mv temp/.* ./

Serving the application

To server your Laravel application and make it accessible to your host's browser, run:

php artisan serve --host=0.0.0.0
This command starts Laravel's built-in development server, making it accessible through your local machine at localhost:8000.

0 Comments

Add a new comment: