Docker for an existing Laravel app · Part 3 of 3

Tooling8 min read

Daily use for a team

One script for every command, a new teammate running the app in one command, why files stay yours, Xdebug when you need it, a variant for macOS, and the failures people hit with what each one means.

By Abhishek Fouzdar · Updated

The stack from parts 1 and 2 works. This part is about living with it as a team: the script that stands in for every command, what a new teammate does on day one, why files stay yours, how to run tests and read logs, Xdebug for the days you need it, a variant for macOS, and the failures people hit, each with its cause.

One script

Nobody should type docker compose exec app php artisan migrate. Create bin/dev and make it executable with chmod +x bin/dev:

#!/usr/bin/env bash
# The one command the team uses. Everything runs inside the containers.
#
#   bin/dev up              start the stack (build on first run), then migrate
#   bin/dev down            stop it; data stays in the db volume
#   bin/dev artisan …       php artisan inside app
#   bin/dev composer …      composer inside app
#   bin/dev npm …           npm inside node
#   bin/dev test            the test suite
#   bin/dev shell           a shell inside app
#   bin/dev mysql           a mysql client on the database
#   bin/dev logs [service]  follow output
#   bin/dev fresh           drop everything including the database and start over
set -euo pipefail
cd "$(dirname "$0")/.."

# Containers write files as this user, so they stay yours on the host.
export DOCKER_UID="$(id -u)" DOCKER_GID="$(id -g)"

[ -f .env ] || { cp .env.example .env; echo "Created .env from .env.example"; }

# Host ports from .env, so the messages below say where things actually are.
APP_HOST_PORT="$(grep -E "^APP_HOST_PORT=" .env | cut -d= -f2)"
MAIL_HOST_PORT="$(grep -E "^MAIL_HOST_PORT=" .env | cut -d= -f2)"
export DOCKER_XDEBUG="$(grep -E "^DOCKER_XDEBUG=" .env | cut -d= -f2)"

case "${1:-}" in
  up)
    docker compose up -d --build --wait
    docker compose exec app php artisan key:generate --no-interaction --ansi >/dev/null 2>&1 || true
    docker compose exec app php artisan migrate --no-interaction --ansi
    echo "App: http://localhost:${APP_HOST_PORT:-8080}   Mail: http://localhost:${MAIL_HOST_PORT:-8025}"
    ;;
  down)     docker compose down ;;
  fresh)    docker compose down -v --remove-orphans && "$0" up ;;
  artisan)  shift; docker compose exec app php artisan "$@" ;;
  composer) shift; docker compose exec app composer "$@" ;;
  npm)      shift; docker compose exec node npm "$@" ;;
  test)     shift; docker compose exec app php artisan test "$@" ;;
  shell)    docker compose exec app sh ;;
  mysql)    docker compose exec db sh -c 'mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE"' ;;
  logs)     shift; docker compose logs -f --tail=100 "$@" ;;
  *)        sed -n '2,13p' "$0"; exit 1 ;;
esac

Four things it does that matter.

It exports your user and group ids before every command, so the image is built with them and every container runs as you. Nobody has to remember.

It creates .env from .env.example when there is none. Combined with the entrypoint from part 1, this is what makes onboarding one command.

up builds, waits, generates a key if needed, and migrates. key:generate is harmless when a key exists; it refuses to overwrite one. Migrating on every up means a teammate who pulls a branch with a new migration gets it applied the next time they start.

fresh deletes the database volume and starts over. It is the only destructive command in the file and it says so.

Add the commands your project uses. If you run Pint and PHPStan, lint and analyse go in the same place.

Day one for a new teammate

The instructions in the README are now three lines:

git clone <repo> app && cd app
bin/dev up

Here is what happens on a clone with no vendor/, no node_modules/ and no .env, timed on a machine that had the images cached:

Created .env from .env.example
 Container app-db-1       Healthy
 Container app-redis-1    Healthy
 Container app-app-1      Healthy
 ...
   INFO  Running migrations.
App: http://localhost:8080   Mail: http://localhost:8025

Forty-two seconds. On a machine that has never built the image it is a few minutes, most of it compiling PHP extensions, once. During that first start app reports unhealthy while Composer installs; --wait holds until it is done, then the worker and scheduler start, then the migrations run. Open the app, open Mailpit, run the tests. Nothing else to install, nothing to configure, no wiki page.

Why the files stay yours

Run ls -ln storage/logs vendor node_modules on the host after the stack has written to them. Every file shows your uid. This is the result of three small decisions made earlier: the Dockerfile re-numbers www-data to the ids passed in; compose.yaml passes DOCKER_UID and DOCKER_GID; bin/dev sets them from id -u and id -g. If you ever build without the script, or on a machine where your uid is not 1000 and the defaults kick in, you will know within minutes: a log file you cannot delete, a compiled view you cannot overwrite. The fix is to build again through the script.

The daily commands

bin/dev artisan make:model Order -m     # scaffolding, inside the container
bin/dev artisan migrate                 # after pulling a branch with migrations
bin/dev composer require spatie/laravel-permission
bin/dev npm install some-package
bin/dev test                            # or: bin/dev test --filter=OrderTest
bin/dev logs queue                      # watch the worker
bin/dev logs                            # everything
bin/dev mysql                           # a MySQL prompt on the app database
bin/dev shell                           # a shell as www-data in the app container
bin/dev artisan tinker

Two habits to pass on. After git pull, if composer.lock changed, run bin/dev composer install: the entrypoint only installs when vendor/ is missing, never when it is stale. And after editing a job class, docker compose restart queue, or wait for the hourly restart from part 2.

One thing the stack does not change: Laravel's phpunit.xml points the tests at SQLite in memory, so bin/dev test needs nothing else running, but the suite never sees the MySQL the app runs on. Moving it onto a testing database in the same container is a small change, one phpunit.xml edit, an init script and one volume line, covered in part 1 of the CI/CD series.

Xdebug, when you need it

Step debugging through a container works, and it is a build-time option because Xdebug slows PHP noticeably even when idle. Add to the Dockerfile, just before the Composer COPY:

# Optional: Xdebug, only when built with XDEBUG=1 (bin/dev reads DOCKER_XDEBUG from .env).
# It is a build-time choice because the extension costs noticeable speed even when idle.
ARG XDEBUG=0
RUN if [ "$XDEBUG" = "1" ]; then \
        apk add --no-cache --virtual .xdebug-deps $PHPIZE_DEPS linux-headers \
        && pecl install xdebug \
        && docker-php-ext-enable xdebug \
        && apk del .xdebug-deps; \
    fi
COPY docker/php/xdebug.ini /usr/local/etc/php/conf.d/zz-xdebug.ini

Create docker/php/xdebug.ini:

; Read only when the xdebug extension is loaded (XDEBUG=1 at build time).
; Debugging starts on request, not on every request: set the XDEBUG_TRIGGER cookie,
; query string or environment variable from your editor's browser extension.
xdebug.mode = debug
xdebug.start_with_request = trigger
xdebug.client_host = host.docker.internal
xdebug.client_port = 9003

The ini file is copied whether or not the extension is built; PHP ignores settings for an extension that is not loaded. In compose.yaml, pass the argument and give the containers a route back to your machine, both inside the x-php block:

    args:
      UID: "${DOCKER_UID:-1000}"
      GID: "${DOCKER_GID:-1000}"
      XDEBUG: "${DOCKER_XDEBUG:-0}"
  # Lets a container reach your editor on the host, for Xdebug.
  extra_hosts:
    - "host.docker.internal:host-gateway"

host.docker.internal is how a container addresses the host. Docker Desktop provides it; on Linux the extra_hosts line creates it. Add DOCKER_XDEBUG=0 to .env.example; a teammate who wants the debugger sets it to 1 and runs bin/dev up, which rebuilds the image with the extension. php -m inside the container lists xdebug only in that build.

In the editor, map the path /var/www/html to your project folder and listen on port 9003. start_with_request = trigger means nothing happens until the request carries a trigger, so the debugger does not slow every page; the browser extensions for PhpStorm and VS Code set the trigger with one click.

Teammates on macOS and Windows

On Linux a bind mount is the filesystem itself, and this stack is fast. On macOS and Windows, Docker runs in a virtual machine and the bind mount crosses into it, which is slow for directories with tens of thousands of small files. vendor/ and node_modules/ are exactly that. The usual fix keeps them in named volumes inside the VM while the rest of the project stays bind-mounted and editable.

Create compose.macos.yaml:

# For teammates on macOS (and Windows), where a bind mount is slow for directories with
# tens of thousands of small files. vendor/ and node_modules/ move into named volumes
# that live inside Docker's VM; the rest of the project stays bind-mounted and editable.
# The trade: the host no longer sees vendor/, so point your editor's PHP interpreter at
# the container, or run `bin/dev composer install` once on the host for autocompletion.
#
#   COMPOSE_FILE=compose.yaml:compose.macos.yaml bin/dev up
#
# (put that line in your shell profile, or export it in .env as COMPOSE_FILE)
services:
  app:
    volumes:
      - vendor:/var/www/html/vendor
  queue:
    volumes:
      - vendor:/var/www/html/vendor
  scheduler:
    volumes:
      - vendor:/var/www/html/vendor
  node:
    # Root, so npm can write into the fresh named volume. On Docker Desktop files it
    # writes to the bind mount still appear as yours on the host.
    user: root
    volumes:
      - node_modules:/var/www/html/node_modules

volumes:
  vendor:
  node_modules:

A volume mounted on top of a bind mount hides that path inside the container, so the container's vendor/ is the volume and the host's vendor/ is untouched. Two details took a few attempts to get right, which is why they are in the file. A fresh named volume is owned by root unless the image already has a directory at that path with the right owner; the mkdir -p /var/www/html/vendor in the part 1 Dockerfile is there for this. And the Node image has no such directory, so under this override node runs as root, which on Docker Desktop is harmless because file ownership on bind mounts is mapped to the host user anyway.

The override was built and tested on Linux, where it works but is unnecessary. On macOS the behaviour is the same with the speed difference it exists for. The trade is that the host's vendor/ no longer matches the container's, so an editor's autocompletion needs either an interpreter configured to run inside the container, or a one-time composer install on the host.

When it does not work

Every one of these happened while building this series.

"address already in use" on up. Something on your machine already listens on 8080, 3306, 5173 or 8025. Set APP_HOST_PORT, DB_HOST_PORT, VITE_HOST_PORT or MAIL_HOST_PORT in .env to a free port and run up again. Change APP_URL if you changed the app port.

502 Bad Gateway right after up. nginx is up, PHP is not ready. Usually the entrypoint is still running composer install on a fresh clone; bin/dev logs app shows it. --wait in the script exists to prevent this, so if you see it, you ran docker compose up without --wait.

"No application encryption key has been specified", even after key:generate. The key is in .env but the container's environment has an empty APP_KEY that was injected at start and takes precedence. You have env_file: .env in compose.yaml. Remove it; Laravel reads the file itself.

"SQLSTATE[HY000] [2002] Connection refused". DB_HOST is 127.0.0.1 or localhost. Inside the app container that is the app container. Set DB_HOST=db. The same applies to REDIS_HOST=redis and MAIL_HOST=mailpit.

Assets fail to load, or the page requests http://0.0.0.0:5173. hmr.host is not set in vite.config.js, so the hot file names the wrong address. Add hmr: { host: 'localhost' }.

Hot reload never fires. No usePolling: true. The bind mount does not deliver file events into the container.

The worker keeps failing on a bug you already fixed. It is running the code it loaded at start. docker compose restart queue.

The node container restarts forever. node_modules/ exists but is empty, so the install was skipped and vite is missing. The guard in part 2 checks for node_modules/.bin/vite rather than the directory; if yours checks the directory, change it.

Files owned by root, or by uid 82. The image was built without your ids, usually by running docker compose directly instead of through bin/dev. Build again through the script; fix the existing files once with sudo chown -R $(id -u):$(id -g) storage bootstrap/cache.

"Permission denied" installing into a named volume. The volume was created root-owned because the image had no directory at the mount path. Add the mkdir to the Dockerfile and docker volume rm the bad volume.

migrate says a table already exists after fresh. It did not run fresh; it ran down, which keeps the volume. fresh is down -v.

Checkpoint

You should have:

  • bin/dev with the commands above, executable, used by everyone;
  • a README that says bin/dev up;
  • optionally Xdebug behind DOCKER_XDEBUG, and compose.macos.yaml for the teammates who need it.

What you have

An existing Laravel app, unchanged in its code, that any teammate can run with Docker and one command: the same PHP, MySQL, Redis and Node for everyone, the worker and scheduler always running, every mail caught, hot reload working, and the files on disk still yours. The next series takes the same app and makes a machine run its tests and deploy it.

New posts by email

Get new posts by email. Nothing else, no digests, unsubscribe in one click.

Comments

Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.