Docker for an existing Laravel app · Part 2 of 3

Tooling6 min read

Redis, the worker, the scheduler, Vite and Mailpit

The rest of the development stack: a queue worker that is always running, the scheduler, hot reload that actually fires through a bind mount, and an inbox for every mail the app sends.

By Abhishek Fouzdar · Updated

Part 1 got the app answering from containers. This part adds the services that make it a complete development environment: Redis for cache, sessions and the queue, a queue worker that is always running, the scheduler, the Vite dev server with hot reload that actually fires, and Mailpit so you can read every mail the app sends. By the end a request to a route dispatches a job, the worker sends a mail, and the mail appears in an inbox in your browser.

Sharing the PHP definition

Three containers will run the same PHP image: the web app, the worker and the scheduler. Compose has a way to write a block once and reuse it. Replace the top of compose.yaml with this:

name: app

# Shared by every PHP container: one image, one bind mount, one set of ids.
x-php: &php
  build:
    context: .
    dockerfile: docker/php/Dockerfile
    args:
      UID: "${DOCKER_UID:-1000}"
      GID: "${DOCKER_GID:-1000}"
  # No env_file: Laravel reads .env from the bind mount itself. Injecting the file here
  # would freeze its values into the container environment, where they shadow later
  # edits to the file. APP_KEY after key:generate is the one that bites.
  volumes:
    - .:/var/www/html
  restart: unless-stopped

x-php is an extension field, ignored by Compose except as something to reference, and &php names it. Each PHP service below starts with <<: *php, which pastes the block in. One image, one bind mount, one pair of ids, so the worker can never end up on a different PHP than the app it works for.

The comment about env_file records a bug that cost an hour. Compose can inject a .env file into a container's environment, and it is tempting, because Laravel's .env is right there. Do not. Environment variables take precedence over the file for Laravel, and they are frozen when the container starts. Run php artisan key:generate, which writes APP_KEY into the file, and the container keeps the empty APP_KEY it started with until it is recreated. The app reads the file from the bind mount perfectly well on its own.

The app service becomes:

  app:
    <<: *php
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
    # "Healthy" means the entrypoint has finished installing vendor/. The worker and
    # the scheduler wait for this, so they never run composer over the same mount.
    healthcheck:
      test: ["CMD-SHELL", "test -f vendor/autoload.php"]
      interval: 3s
      timeout: 5s
      start_period: 300s
      retries: 3

Redis

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 20
    restart: unless-stopped

No port is published; nothing on the host needs it. In .env and .env.example, move the three drivers over and point at the service:

SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
CACHE_STORE=redis
REDIS_HOST=redis

The redis PHP extension was compiled into the image in part 1, so this is all it takes. If you prefer to keep the database drivers, keep the redis service (the app block above depends on it) and skip only the .env change; everything else still works, and the worker reads from whichever queue connection .env names.

The queue worker

  # The queue worker: the same image as app, running artisan instead of php-fpm.
  # --max-time makes it exit every hour; restart: unless-stopped brings it back with
  # fresh code, which is the simplest answer to "my worker is running old code".
  queue:
    <<: *php
    command: php artisan queue:work --tries=3 --max-time=3600
    depends_on:
      app:
        condition: service_healthy

The same image, a different command. command: replaces the Dockerfile's php-fpm with queue:work, and the entrypoint still runs first, so a fresh clone cannot start the worker on an empty vendor/. It waits on app being healthy for the same reason, and because two containers running composer install into the same mount at the same time ends badly.

A long-running worker keeps the code it loaded at start. Edit a job class and the worker keeps running the old version until it restarts, which is the classic "I fixed it but it still fails" moment. --max-time=3600 makes it exit cleanly every hour and restart: unless-stopped brings it back. For an immediate reload, docker compose restart queue.

The scheduler

  # The scheduler: schedule:work wakes every minute and runs what routes/console.php
  # declares as due. Same image again, so it cannot drift from the app.
  scheduler:
    <<: *php
    command: php artisan schedule:work
    depends_on:
      app:
        condition: service_healthy

In production the scheduler is a cron entry that runs schedule:run every minute. schedule:work is Laravel's long-running equivalent: it wakes every minute and runs whatever is due. No cron in the container, no extra image. If your app has a scheduled command, it now runs locally without anyone remembering to start it.

Vite with hot reload

  # Vite. Installs node_modules on first start so `bin/dev up` is one command on a
  # clean clone. Host, port and polling are set in vite.config.js.
  node:
    image: node:22-alpine
    working_dir: /var/www/html
    user: "${DOCKER_UID:-1000}:${DOCKER_GID:-1000}"
    volumes:
      - .:/var/www/html
    # Checks for a file, not the directory: an empty node_modules/ (a fresh named volume,
    # or a clone that once had one) must still trigger the install.
    command: sh -c "[ -f node_modules/.bin/vite ] || npm install; npm run dev"
    environment:
      VITE_HOST_PORT: "${VITE_HOST_PORT:-5173}"
    ports:
      - "${VITE_HOST_PORT:-5173}:${VITE_HOST_PORT:-5173}"
    restart: unless-stopped

The stock Node image, running as your user so node_modules/ and public/hot are yours, with an install guard like the PHP entrypoint's. The guard checks for a file inside node_modules, not the directory: an empty directory exists in more situations than you would think, and npm run dev on one fails in a restart loop.

The Vite config needs three changes to work from inside a container. Edit vite.config.js:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';

// Inside Docker the dev server must listen on every interface (so the published port
// reaches it), but the browser on the host must be told to connect to localhost, not to
// 0.0.0.0. The port follows VITE_HOST_PORT so the hot file names the published port.
const port = Number(process.env.VITE_HOST_PORT ?? 5173);

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
        tailwindcss(),
    ],
    server: {
        host: '0.0.0.0',
        port,
        strictPort: true,
        hmr: { host: 'localhost' },
        watch: {
            usePolling: true,
            ignored: ['**/storage/framework/views/**', '**/vendor/**'],
        },
    },
});

Each line fixes a specific failure.

host: '0.0.0.0' makes Vite listen on all interfaces inside the container. By default it listens on localhost, which inside the container is unreachable from your browser.

hmr: { host: 'localhost' } is the other half. Laravel's Vite plugin writes the dev server's address into public/hot, and the Blade @vite directive uses it to build script tags. Without this line the file says http://0.0.0.0:5173, and the browser is asked to load assets from an address that only works by accident on some systems. With it, the page loads from http://localhost:5173 everywhere.

usePolling: true is why hot reload fires at all. A bind mount does not pass the host's file-change notifications into the container, so Vite's watcher never hears about your edits. Polling checks for changes on a timer instead. It costs a little CPU and is the difference between hot reload working and not. vendor/ is excluded from the polling because it is huge and never changes under Vite.

The port follows VITE_HOST_PORT so that a teammate who moves it, because 5173 is taken on their machine, gets a hot file that names the port they actually published.

Mailpit

  # Catches every mail the app sends. Inbox at http://localhost:8025.
  mailpit:
    image: axllent/mailpit:v1
    ports:
      - "${MAIL_HOST_PORT:-8025}:8025"
    restart: unless-stopped

And in .env and .env.example:

MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025

Mailpit accepts SMTP on 1025 and shows what it received at http://localhost:8025. Every mail the app sends in development lands there, with its HTML rendered, and nothing ever reaches a real address.

The ports block

Every published port can be moved from .env, so add the defaults to .env.example where a teammate will see them:

# Host ports the stack publishes. Change these when something on your machine already
# uses one; nothing inside the containers cares.
APP_HOST_PORT=8080
DB_HOST_PORT=3306
VITE_HOST_PORT=5173
MAIL_HOST_PORT=8025

If you change APP_HOST_PORT, change APP_URL to match.

Proving it

Start the new services:

docker compose up -d --build --wait

The example app has a route that dispatches a queued job which sends a mail:

curl http://localhost:8080/signup/[email protected]
Queued a welcome mail for [email protected].

Watch the worker take it:

docker compose logs queue --tail=5
queue-1  |   2026-10-22 16:53:41 App\Jobs\SendWelcomeMail ....................... RUNNING
queue-1  |   2026-10-22 16:53:41 App\Jobs\SendWelcomeMail ................. 241.35ms DONE

Open http://localhost:8025. The welcome mail is in the inbox, rendered. Then the scheduler: the example app logs a heartbeat every minute, so after a minute:

grep heartbeat storage/logs/laravel.log
[2026-10-22 16:54:00] local.INFO: heartbeat {"at":"2026-10-22 16:54:00"}

And Vite: cat public/hot prints http://localhost:5173, and the page's script tags point there. Edit resources/css/app.css and the browser updates without a reload.

Checkpoint

You should have:

  • redis, queue, scheduler, node and mailpit services in compose.yaml, with x-php shared by the three PHP containers;
  • the Redis drivers, Mailpit settings and host ports in .env and .env.example;
  • the three server changes in vite.config.js;
  • a queued mail visible in Mailpit, a heartbeat in the log, and hot reload working.

Everything the app needs now runs with one docker compose up. Part 3 is about the team: a script so nobody types docker compose exec app php artisan, onboarding in one command, Xdebug, macOS, and the failures people hit.

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.