feat: docker compose dev environment

Replaces the bare-metal `composer run dev` workflow with a fully
containerized 9-service stack orchestrated by docker compose. Single
command brings up the full app — three subdomains (marketing /
account / admin) reachable via Traefik with TLS, MariaDB + Valkey
+ Mailpit + Vite HMR + Horizon + scheduler all wired in.

Components:
- docker-compose.yml: traefik, app (php-fpm), web (nginx), mariadb,
  valkey, mailpit, vite, horizon, scheduler.
- docker/: Dockerfiles, nginx config, entrypoint scripts.
- Makefile: convenience targets (up / down / logs / shell / migrate
  / seed / test / pint / etc).
- .env.docker.example: template for Docker-stack environment vars
  (separate from website/.env so bare-metal devs aren't disrupted).
- website/vite.config.ts: server.host / origin / hmr / cors hooks
  driven by VITE_HOST / VITE_ORIGIN / VITE_HMR_HOST so the same
  config serves both bare-metal and Docker.
- website/bootstrap/app.php: redirectGuestsTo() now uses
  request()->getScheme() so http: dev hosts don't get force-https
  redirects.
- composer.json: drops laravel/sail (replaced by this stack).
- docs/superpowers/specs/2026-04-25-docker-compose-dev-environment-design.md:
  full design spec.

Bare-metal `composer run dev` workflow stays usable for anyone who
prefers it — Docker stack reads .env.docker, doesn't fight
website/.env.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-26 22:10:53 -04:00
parent 4b98e52043
commit dfdef3d7f4
21 changed files with 1975 additions and 741 deletions

142
docker/README.md Normal file
View File

@@ -0,0 +1,142 @@
# EZSCALE — Docker Compose Dev Environment
Multi-service development stack for the EZSCALE Laravel app. Replaces the bare-metal `composer run dev` workflow with a fully-containerized environment that mirrors the production topology (nginx + PHP-FPM + MariaDB + Valkey + Horizon).
## Prerequisites
- **Docker Engine 24+** with **Compose V2** (`docker compose`, not `docker-compose`)
- **WSL2 with files cloned under `/home/$USER/`** (NOT `/mnt/c/...` — bind-mount performance is unusable on the Windows-mounted filesystem)
- A modern browser (Chrome, Firefox, Safari) — `*.docker.localhost` resolution requires no `/etc/hosts` edits
## First-time setup
```bash
make init
```
That single command:
1. Copies `.env.docker.example``.env.docker`
2. Builds all custom images (PHP-FPM, nginx, vite)
3. Pulls third-party images (Traefik, MariaDB, Valkey, Mailpit)
4. Boots MariaDB and Valkey, waits for them to be healthy
5. Runs `composer install` and `npm install`
6. Brings up the rest of the stack
When `make init` finishes, you should be able to open:
- **https://ezscale.docker.localhost** — marketing site
- **https://account.ezscale.docker.localhost** — customer dashboard
- **https://admin.ezscale.docker.localhost** — admin panel
- **https://account.ezscale.docker.localhost/horizon** — Horizon dashboard
- **https://mail.ezscale.docker.localhost** — Mailpit UI (catches all outgoing email)
- **https://vite.ezscale.docker.localhost** — Vite dev server (for HMR)
- **http://localhost:8080** — Traefik dashboard (insecure, dev-only)
The first time you visit any of these, your browser will warn about a self-signed cert. Accept once — Traefik issues a wildcard cert covering all subdomains.
## Daily commands
```bash
make up # bring stack up
make down # stop (volumes preserved)
make logs # tail all logs
make logs SVC=horizon # tail one service
make sh # bash inside app container
make artisan ARGS="migrate" # any artisan command
make composer ARGS="require foo/bar"
make npm ARGS="install foo"
make test # php artisan test --compact
make pint # format dirty PHP
make fresh # migrate:fresh --seed
make destroy # nuclear: stop + wipe volumes
```
`make help` prints the full list.
## Architecture
| Service | Image | Role |
|---------|-------|------|
| `traefik` | `traefik:v3.6` | Edge proxy + TLS termination + routing |
| `app` | custom (PHP 8.3-FPM Debian) | Application container |
| `web` | `nginx:1.30-alpine` | Serves `public/`, proxies PHP |
| `vite` | custom (Node 24 Alpine) | HMR dev server |
| `horizon` | same as `app` | Queue worker supervisor |
| `scheduler` | same as `app` | `schedule:work` runner |
| `mariadb` | `mariadb:12` | Primary database |
| `valkey` | `valkey/valkey:9-alpine` | Sessions/cache/queues |
| `mailpit` | `axllent/mailpit:v1.29` | SMTP catcher |
Traefik routes the three Laravel subdomains (marketing/account/admin) to the same nginx container. Laravel's `Route::domain()` in `bootstrap/app.php` handles per-subdomain dispatch internally.
## Environment
The stack reads `.env.docker` at the repo root — separate from `website/.env`. This keeps the Docker workflow from fighting any bare-metal `composer run dev` setup you might still want to use.
Critical Docker-specific values:
```
DB_HOST=mariadb
REDIS_HOST=valkey
MAIL_HOST=mailpit
APP_URL=https://ezscale.docker.localhost
```
Third-party API keys (Stripe, PayPal, VirtFusion, etc.) need to be added to your `.env.docker` if you want to test those integrations.
## Volumes
Persisted across `make down` (lost only on `make destroy`):
- `mariadb_data` — MySQL data
- `valkey_data` — Valkey AOF persistence
- `mailpit_data` — captured email
- `traefik_certs` — self-signed cert cache
The Laravel source (`./website`) is bind-mounted live — your edits show up immediately. `vendor/` and `node_modules/` are visible on the host for IDE autocomplete.
## TLS
Traefik auto-generates a single self-signed wildcard cert for `*.ezscale.docker.localhost` on first boot. The cert lives in the `traefik_certs` volume.
If you want a green-padlock experience instead of accepting the warning once per browser:
```bash
brew install mkcert # or apt/winget equivalent
mkcert -install
mkcert -cert-file docker/traefik/certs/cert.pem \
-key-file docker/traefik/certs/key.pem \
"ezscale.docker.localhost" "*.ezscale.docker.localhost"
```
Then update `docker/traefik/dynamic.yml` to point `certificates:` at those files. Currently configured for self-signed; mkcert is left as a future enhancement.
## Common gotchas
**Port 80 or 443 already in use.**
Edit `docker-compose.yml`'s `traefik` service and remap to e.g. `8000:80`, `8443:443`. Then access the stack at `https://ezscale.docker.localhost:8443`.
**`make init` hangs on "waiting for mariadb".**
First MariaDB boot creates the system tablespace and can take 20-30s. The healthcheck has a 30s `start_period` to accommodate this. If it really stalls, `make logs SVC=mariadb` to see why.
**Permission errors on `storage/logs/laravel.log`.**
The PHP container's UID matches your host UID (1000) by default. If your host UID differs, rebuild with `UID=$(id -u) GID=$(id -g) make build`.
**Horizon dashboard 403s.**
Horizon's gate is in `App\Providers\HorizonServiceProvider::gate()`. In dev all admin users have access; you need to log in with an admin role first.
**Vite assets don't load.**
Check `make logs SVC=vite`. The Laravel Vite plugin auto-injects the dev URL — if it can't reach `https://vite.ezscale.docker.localhost`, assets fall back to the manifest. Make sure that hostname is reachable in your browser.
**Composer/npm install slow.**
First-time `composer install` takes 1-2 min. After that the `vendor/` dir is cached on disk. Same for `node_modules`.
## Co-existing with bare-metal dev
This stack does NOT delete or modify `website/.env`. If you previously used `cd website && composer run dev`, that still works — it reads `website/.env` and connects to whatever local PHP/MySQL/Redis you had.
Pick one or the other for any given session. Don't run both simultaneously (they'd fight over ports and sessions).
## Spec
Full design rationale in [`docs/superpowers/specs/2026-04-25-docker-compose-dev-environment-design.md`](../docs/superpowers/specs/2026-04-25-docker-compose-dev-environment-design.md).

64
docker/app/Dockerfile Normal file
View File

@@ -0,0 +1,64 @@
FROM php:8.3-fpm-bookworm
ARG UID=1000
ARG GID=1000
ENV COMPOSER_ALLOW_SUPERUSER=1 \
COMPOSER_NO_INTERACTION=1 \
COMPOSER_MEMORY_LIMIT=-1
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
git \
unzip \
curl \
ca-certificates \
libzip-dev \
libpng-dev \
libjpeg-dev \
libfreetype6-dev \
libwebp-dev \
libicu-dev \
libonig-dev \
libxml2-dev \
libcurl4-openssl-dev \
libssl-dev \
pkg-config \
&& rm -rf /var/lib/apt/lists/*
RUN docker-php-ext-configure gd --with-freetype --with-jpeg --with-webp \
&& docker-php-ext-install -j"$(nproc)" \
pdo_mysql \
intl \
bcmath \
gd \
zip \
pcntl \
posix \
exif \
sockets \
opcache
RUN pecl install redis \
&& docker-php-ext-enable redis
COPY --from=composer:2 /usr/bin/composer /usr/local/bin/composer
RUN groupmod -g ${GID} www-data \
&& usermod -u ${UID} -g ${GID} www-data \
&& mkdir -p /var/www/.composer \
&& chown -R www-data:www-data /var/www
COPY php.ini /usr/local/etc/php/conf.d/zz-app.ini
COPY opcache.ini /usr/local/etc/php/conf.d/zz-opcache.ini
COPY php-fpm.conf /usr/local/etc/php-fpm.d/zz-app.conf
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
WORKDIR /var/www/html
USER www-data
EXPOSE 9000
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["php-fpm"]

55
docker/app/entrypoint.sh Normal file
View File

@@ -0,0 +1,55 @@
#!/bin/sh
set -e
# ==============================================================================
# EZSCALE app container entrypoint
# Used by `app`, `horizon`, and `scheduler` services. Idempotent.
# ==============================================================================
cd /var/www/html
# Wait for MariaDB. depends_on: condition: service_healthy already gates this,
# but the belt-and-braces loop is cheap and survives healthcheck regressions.
if [ -n "${DB_HOST:-}" ]; then
echo "[entrypoint] waiting for ${DB_HOST}:${DB_PORT:-3306}..."
until php -r "new PDO('mysql:host=${DB_HOST};port=${DB_PORT:-3306}', '${DB_USERNAME}', '${DB_PASSWORD}');" 2>/dev/null; do
sleep 1
done
echo "[entrypoint] mariadb is up."
fi
# Bootstrap .env on first boot. We bind-mount the website/ source, so .env may
# already exist from a previous bare-metal `composer run dev` workflow.
if [ ! -f .env ]; then
if [ -f /var/www/html/.env.docker ]; then
echo "[entrypoint] copying .env.docker -> .env"
cp /var/www/html/.env.docker .env
elif [ -f .env.example ]; then
echo "[entrypoint] copying .env.example -> .env (fallback)"
cp .env.example .env
fi
fi
# Vendor dir bootstrapping — first-clone convenience. Skipped if already present.
if [ ! -d vendor ] || [ ! -f vendor/autoload.php ]; then
echo "[entrypoint] vendor/ missing; running composer install"
composer install --no-interaction --prefer-dist --no-progress
fi
# Generate APP_KEY if blank. `key:generate` writes to .env in place.
if ! grep -qE '^APP_KEY=base64:' .env; then
echo "[entrypoint] generating APP_KEY"
php artisan key:generate --force --no-interaction
fi
# Run migrations only when this container is the `app` (php-fpm) role.
# Horizon and scheduler share this image but skip migrations to avoid races.
case "$1" in
php-fpm|php-fpm*)
echo "[entrypoint] running migrations"
php artisan migrate --force --no-interaction || true
php artisan storage:link || true
;;
esac
exec "$@"

18
docker/app/opcache.ini Normal file
View File

@@ -0,0 +1,18 @@
; ==============================================================================
; OPcache — DEV configuration
; In prod, flip validate_timestamps to 0 and lock the cache.
; ==============================================================================
opcache.enable = 1
opcache.enable_cli = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 32
opcache.max_accelerated_files = 20000
; Recheck files on every request — edits show up immediately
opcache.validate_timestamps = 1
opcache.revalidate_freq = 0
opcache.fast_shutdown = 1
opcache.jit = tracing
opcache.jit_buffer_size = 100M

23
docker/app/php-fpm.conf Normal file
View File

@@ -0,0 +1,23 @@
; ==============================================================================
; PHP-FPM pool — DEV configuration
; ==============================================================================
[www]
user = www-data
group = www-data
listen = 9000
listen.backlog = 511
pm = dynamic
pm.max_children = 25
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 8
pm.max_requests = 1000
; Surface FPM logs to stdout/stderr so `docker compose logs app` shows them
access.log = /proc/self/fd/2
catch_workers_output = yes
decorate_workers_output = no
clear_env = no

24
docker/app/php.ini Normal file
View File

@@ -0,0 +1,24 @@
; ==============================================================================
; EZSCALE dev overrides — applied AFTER php.ini-development
; ==============================================================================
memory_limit = 512M
max_execution_time = 120
post_max_size = 50M
upload_max_filesize = 50M
max_input_vars = 5000
display_errors = On
display_startup_errors = On
error_reporting = E_ALL
log_errors = On
date.timezone = UTC
; Session handling delegated to Laravel; keep PHP-side defaults sane
session.cookie_httponly = 1
session.cookie_samesite = "Lax"
; Realpath cache helps Composer/Laravel reload cycles
realpath_cache_size = 4096K
realpath_cache_ttl = 600

View File

@@ -0,0 +1,9 @@
-- Runs once on first MariaDB volume bootstrap.
-- Creates the testing database used by `php artisan test`.
CREATE DATABASE IF NOT EXISTS ezscale_billing_testing
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
GRANT ALL PRIVILEGES ON ezscale_billing_testing.* TO 'ezscale'@'%';
FLUSH PRIVILEGES;

8
docker/nginx/Dockerfile Normal file
View File

@@ -0,0 +1,8 @@
FROM nginx:1.30-alpine
RUN rm -f /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d/ /etc/nginx/conf.d/
EXPOSE 80

View File

@@ -0,0 +1,54 @@
# ==============================================================================
# EZSCALE catch-all server block
# Traefik routes all 3 subdomains (marketing/account/admin) here. Laravel's
# Route::domain() in bootstrap/app.php handles per-subdomain dispatch.
# ==============================================================================
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /var/www/html/public;
index index.php index.html;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "strict-origin-when-cross-origin";
charset utf-8;
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php-upstream;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
fastcgi_param HTTP_PROXY "";
# Match Traefik forwarded headers
fastcgi_param HTTPS $http_x_forwarded_proto;
fastcgi_param REMOTE_ADDR $http_x_forwarded_for;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
fastcgi_read_timeout 300;
}
# Deny dotfiles except .well-known (LE/CSP)
location ~ /\.(?!well-known).* {
deny all;
access_log off;
log_not_found off;
}
}

40
docker/nginx/nginx.conf Normal file
View File

@@ -0,0 +1,40 @@
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$host"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off;
# Traefik handles compression at the edge — leave it off here.
gzip off;
# 50M for file uploads (matches php upload_max_filesize)
client_max_body_size 50M;
# Upstream PHP-FPM
upstream php-upstream {
server app:9000;
}
include /etc/nginx/conf.d/*.conf;
}

View File

@@ -0,0 +1,17 @@
# ==============================================================================
# Traefik dynamic config — TLS options + self-signed wildcard cert
# ==============================================================================
tls:
options:
default:
minVersion: VersionTLS12
sniStrict: false
stores:
default:
defaultGeneratedCert:
resolver: ""
domain:
main: "ezscale.docker.localhost"
sans:
- "*.ezscale.docker.localhost"

View File

@@ -0,0 +1,33 @@
# ==============================================================================
# Traefik static config — DEV
# ==============================================================================
global:
checkNewVersion: false
sendAnonymousUsage: false
api:
dashboard: true
insecure: true # Dev-only: dashboard at :8080 with no auth
log:
level: INFO
accessLog: {}
entryPoints:
web:
address: ":80"
websecure:
address: ":443"
traefik:
address: ":8080"
providers:
docker:
exposedByDefault: false
network: ezscale
watch: true
file:
filename: /etc/traefik/dynamic.yml
watch: true

16
docker/vite/Dockerfile Normal file
View File

@@ -0,0 +1,16 @@
FROM node:24-alpine
ARG UID=1000
ARG GID=1000
RUN apk add --no-cache git \
&& deluser --remove-home node 2>/dev/null || true \
&& addgroup -g ${GID} node \
&& adduser -D -u ${UID} -G node node
WORKDIR /var/www/html
USER node
EXPOSE 5173
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]