Use an existing Laravel app with Laravel Sail

Tobias Etzold • July 28, 2024

linux laravel

Most of the time, when I work on my side projects in PHP, I use Herd on my Mac to run it. But lately I wanted to try out how good development on my Windows machine is. To test this, I installed Ubuntu under WSL2 on it and added Docker. The next step was to clone an existing repository onto this machine. But what I do not want is to install PHP directly in the Ubuntu subsystem. I just want to do everything in Docker.

First we need to install all vendor packages via composer. For this, there is an example command in Sails documentation.

docker run --rm \
    -u "$(id -u):$(id -g)" \
    -v "$(pwd):/var/www/html" \
    -w /var/www/html \
    laravelsail/php83-composer:latest \
    composer install --ignore-platform-reqs

This command runs the composer install command in a docker container and ignores all possible plattform requirements.

Now we want to use docker with Sail for the first time. Since the command php artisan sail:install is interactive we need to add some arguments to allow interactivity when running in Docker. This is done through --interactiveand --tty

docker run --rm --interactive --tty \
    -u "$(id -u):$(id -g)" \
    -v "$(pwd):/var/www/html" \
    -w /var/www/html \
    laravelsail/php83-composer:latest \
    php artisan sail:install

Now we can select parts of our stack we want to run in Docker. This can be a database like MySQL, PostgreSQL or a service like Mailpit. Select what you need with spacebar und run it afterward with enter.

When this is done we can run Laravel Sail with ./vendor/bin/sail up -d. Since under the hood Laravel Sail uses Docker compose the argument -d runs your Docker container in detached mode. In other words, it will run in the background. To stop your container just run ./vendor/bin/sail stop.

If you prefer a shorter form you can set up an alias in your shells rc file. For example your .bashrc or .zshrc.

alias sail='sh $([ -f sail ] && echo sail || echo vendor/bin/sail)'

Now you can use your existing Laravel app with Sail.

PS: When you want to start Sail on a Laravel code base where Sail was not already installed, you will get an error message like no configuration file provided: not found. This is because Sail misses a docker-compose.yml file. In this case you just need to run php artisan sail:install if you already installed PHP locally. Alternatively run the provided interactive installation command provided earlier.