Testing and operations
Deployment
This page takes a Taphra app to a production server: the web server and its document root, the environment, the steps to run on every deploy, OPcache preloading, FrankenPHP worker mode, file permissions, logs, queue workers and the scheduler, and Docker. The security settings to review before going live are in the production checklist.
Contents
#- Server requirements
- Install the code
- Document root
- Environment
- On every deploy
- OPcache and preloading
- FrankenPHP worker mode
- Files and permissions
- Logs
- Queue workers and the scheduler
- Docker
Server requirements
#- PHP 8.2, 8.3 or 8.4 (the versions the framework is tested on) with
ext-curl,ext-json,ext-mbstring,ext-pdo,ext-sodiumand the PDO driver of your database (pdo_mysql,pdo_pgsql,pdo_sqlite). - OPcache, for production speed.
- Optional:
ext-pcntlfor queue workers that run several processes and stop cleanly on SIGTERM,ext-intlfor full CLDR plural and number formats. - Composer, on the server or wherever you build the release.
Install the code
#composer install --no-dev --optimize-autoloader --no-interaction--no-dev leaves out development packages. --optimize-autoloader builds a complete class map, which also covers class files named *.class.php (the skeleton's own controllers and DataStores use that name, and Composer finds those only through its class map).
Run Composer with the PHP version the server runs, or pin it in composer.json with "config": {"platform": {"php": "8.2.0"}}. A lock file resolved on PHP 8.4 can pick dependency versions that refuse to load on 8.2 or 8.3.
The four starters ship with that setting, so composer create-project and composer update resolve the lock for PHP 8.2 whatever PHP runs them, and the lock installs on 8.2, 8.3 and 8.4. When every machine that installs the app runs a newer PHP, raise the version ("php": "8.4.0") and run composer update to allow packages that need it.
Document root
#The web server's document root is app/Static. It holds index.php, the front controller, and your public assets (CSS, JavaScript, images). Every request that is not a file in that folder goes to index.php, which routes on the request URI. Nothing outside app/Static is served.
nginx and php-fpm
#Pass only index.php to PHP. The folder also contains indexcommon.php (the shared boot file) and frankenphp-worker.php; neither needs to be reachable over HTTP.
server {
listen 80;
server_name example.com;
root /var/www/my-app/app/Static;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# Only the front controller runs as PHP.
location = /index.php {
fastcgi_pass unix:/run/php/php8.4-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_param APP_ENV prod;
}
location ~ \.php$ {
return 404;
}
location ~ /\. {
deny all;
}
}fastcgi_param APP_ENV prod puts the variable where getenv() reads it. You can set it in the php-fpm pool instead (env[APP_ENV] = prod).
Apache
#The skeleton ships app/Static/.htaccess: files and folders that exist are served as they are, every other request goes to index.php. It needs mod_rewrite and AllowOverride All (or at least FileInfo) on the folder:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/my-app/app/Static
SetEnv APP_ENV prod
<Directory /var/www/my-app/app/Static>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>Enable the module with a2enmod rewrite on Debian and Ubuntu.
Environment
#The mode comes from APP_ENV: dev, development or local mean development, stg, stage or staging mean staging, and anything else, including an unset variable, means production. IS_PRODUCTION=1 forces production whatever APP_ENV says. In production:
display_errorsis off (theprod:section of the skeleton'sapp.ymlsets it to 0), uncaught exceptions get the app's error pages (app/Views/error404.tpl.php,error500.tpl.php) and the details go to the log. The debug error page is only registered in development.- The log starts at the notice level (see Logs).
url()builds absolute links fromapp.base_urland throws aTaphra\Exceptions\ConfigurationExceptionwhen it is not set, rather than trusting the request'sHostheader.
Set these in app/Config/app.yml:
prod:
display_errors: 0
protocol: https
domain: example.com
base_url: https://example.com
# Behind a load balancer or reverse proxy, list its addresses (IPs or CIDR ranges):
trusted_proxies: [10.0.0.0/8]trusted_proxies matters behind a proxy. Without it, the client IP is the address of the connection and a request counts as HTTPS only when PHP sees HTTPS (or port 443) itself: X-Forwarded-For and X-Forwarded-Proto are ignored, because any client can send them. With it, those headers are read when the connection comes from a listed proxy, so Request::clientIP(), the HTTPS check and the session cookie's Secure flag see the real client and scheme. RateLimitMiddleware counts per Request::clientIP() too, so with the proxy listed each client gets its own limit; without the list, every client behind the proxy shares the proxy's.
Keep secrets (database passwords, API keys, APP_SECRET_KEY, JWT secrets) out of the YAML files you commit. composer create-project and php taphra key:generate write APP_SECRET_KEY to .env in development. In production, set each variable in the environment of the PHP process: the php-fpm pool, the systemd unit, the container. getenv('APP_SECRET_KEY') then reads it, and app/Config/ai.yml resolves ${ANTHROPIC_API_KEY} style placeholders from the same environment.
The command line reads the same variable, so run deploy commands with it:
export APP_ENV=prodOn every deploy
#composer install --no-dev --optimize-autoloader --no-interaction
php taphra migrate
php taphra optimize
# then restart php-fpm (or FrankenPHP) and the queue workersRun them in the app root with the production APP_ENV.
optimize reads the YAML files in app/Config/ and compiles the config and the routes of the current mode into app/tmp/tphr_frozen.php (routes that packages add from their service providers are not frozen: the providers add them again when they boot). Once that file exists, every request loads config and routes from it in one require, with no YAML parsing and no file checks; a config change takes effect when you run optimize again. It also writes app/tmp/preload.php (see the next section) and the cache files config.cache.php, routes.cache.php and config_cache/*.php.
Without the frozen file (before the first optimize, or after optimize:clear), config is read through caches that record each YAML file's modification time and size, so an edited file is picked up on the next request in every mode, and optimize:clear removes those caches too. A deploy needs no cache:clear for config; that command empties the whole application cache, your own cached values included.
OPcache and preloading
#Enable OPcache in production. optimize writes app/tmp/preload.php, which loads the framework's classes into OPcache when PHP starts, so requests do not compile them again. Point PHP at it in the php-fpm (or FrankenPHP) php.ini:
opcache.enable=1
opcache.preload=/var/www/my-app/app/tmp/preload.php
opcache.preload_user=www-dataThe file contains absolute paths, so generate it in the folder the app runs from (run optimize in each release folder). Preloading happens when PHP starts: restart php-fpm or FrankenPHP after each deploy. If you set opcache.validate_timestamps=0, the restart is also what makes PHP see the new code.
FrankenPHP worker mode
#FrankenPHP can keep the app booted in a worker process and hand it one request after another. The skeleton ships the worker script, app/Static/frankenphp-worker.php: it boots the app once, then for each request calls Taphra\RequestState::reset() and dispatches. Under php-fpm or php -S the same file handles a single request, so it runs anywhere.
Requests have to reach the worker script, not index.php. With php_server, make the worker script the index file, so every request that is not a file under app/Static goes to it:
{
frankenphp
}
example.com {
root * /var/www/my-app/app/Static
encode zstd br gzip
php_server {
index frankenphp-worker.php
worker {
file /var/www/my-app/app/Static/frankenphp-worker.php
}
}
}cd /var/www/my-app
APP_ENV=prod php taphra optimize
APP_ENV=prod frankenphp run --config Caddyfileworker { num 4 } sets the number of worker processes. Restart FrankenPHP after a deploy: a worker keeps the code it booted with.
What persists between requests
#RequestState::reset() runs before every request and resets the request timer, the request ID, the shared database connections (each request opens its own), the query log, the authenticated user of the auth driver, the session of the previous request, the CSP nonce, the validation error bag, the parsed request and pending response headers. FrankenPHP itself refills $_GET, $_POST, $_COOKIE, $_SERVER and $_FILES.
Everything else lives as long as the worker: the loaded config and routes, the service container and its singletons, registered event listeners, and every static property and global variable your own code sets. That is what makes worker mode fast, and it is also the rule for your code: do not keep per-request data (the current user, the current request, a counter) in static properties or singletons, or the next request sees it.
Files and permissions
#app/tmp/ must be writable by the user PHP runs as (www-data on Debian and Ubuntu). It holds the file cache (Filecache/), the logs (Log/), the compiled config (config_cache/, lang_cache/, tphr_frozen.php) and preload.php. If PHP cannot write there, requests fail with the error page.
chown -R www-data:www-data app/tmp
chmod -R ug+rwX app/tmpThe rest of the app can stay read-only for the PHP user.
With session.method: file (the skeleton's default) sessions are PHP's own session files in session.save_path. When several servers serve the app, use database sessions (session.method: database) or a save path they share, so a user's next request finds their session. The same goes for the file cache and file locks: each server has its own app/tmp/, so use Redis or a database backend for anything the servers must share. See Configuration and Cache.
Logs
#The file logger (logging.method: file, the default) writes JSON lines to app/tmp/Log/app.log. In production it writes notices, warnings and errors; set app.logging.level (debug, message, notice, warning or error) to change that. logging.method: syslog sends the lines to syslog or journald instead, and logging.method: null discards them. See Logging.
Each PHP process keeps the log file open, so rotate it with copytruncate:
/var/www/my-app/app/tmp/Log/*.log {
daily
rotate 14
compress
missingok
notifempty
copytruncate
}logging.log_requests: true records every request in app/tmp/Log/requests.log for php taphra debug:request. It is ignored in production.
Queue workers and the scheduler
#php taphra queue:work runs until it is stopped. Keep it running with systemd (or supervisor), restart it when it exits, and restart it on every deploy so it runs the new code. With ext-pcntl, SIGTERM lets the current job finish first.
# /etc/systemd/system/my-app-queue.service
[Unit]
Description=my-app queue worker
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/my-app
Environment=APP_ENV=prod
ExecStart=/usr/bin/php taphra queue:work default --tries=3
Restart=always
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=60
[Install]
WantedBy=multi-user.targetsudo systemctl enable --now my-app-queue
sudo systemctl restart my-app-queue # on every deploy--concurrency=4 runs four worker processes from one unit. Options and drivers are in Queues.
The scheduler needs one cron entry that runs every minute; schedule:run then runs the tasks from app/Console/Kernel.php that are due:
* * * * * cd /var/www/my-app && APP_ENV=prod php taphra schedule:run >> /dev/null 2>&1Put it in the crontab of the PHP user (crontab -u www-data -e). See Scheduler.
Docker
#The skeleton's Dockerfile and docker-compose.yml are for development: they run php taphra serve with APP_ENV=dev next to a MySQL container. The app's databases.yml points at 127.0.0.1; inside Compose the database is the db service, so set host: db and the user and password from docker-compose.yml in the dev: section before you use a DataStore. php taphra make:dockerfile writes a similar development pair for an app that has none, with a MySQL service: the app is published on 127.0.0.1:8080 only, MySQL and Redis get no published port (the app reaches them as db and redis), and the database user's password is DB_PASSWORD in .env, written with a random value when missing (docker compose reads .env, so the password is not in docker-compose.yml).
For production, an image built on FrankenPHP serves the app in worker mode. Put this Caddyfile next to the app's composer.json:
{
frankenphp
}
{$SERVER_NAME::8080} {
root * /app/app/Static
encode zstd br gzip
php_server {
index frankenphp-worker.php
worker {
file /app/app/Static/frankenphp-worker.php
}
}
}a preload.ini:
opcache.enable=1
opcache.preload=/app/app/tmp/preload.php
opcache.preload_user=appand this Dockerfile.prod:
FROM dunglas/frankenphp:1-php8.4
RUN install-php-extensions pdo_mysql zip
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-interaction --no-scripts --no-autoloader
COPY . .
RUN composer dump-autoload --optimize --no-dev \
&& APP_ENV=prod php taphra optimize
COPY Caddyfile /etc/frankenphp/Caddyfile
COPY preload.ini /usr/local/etc/php/conf.d/preload.ini
RUN useradd --system app \
&& chown -R app:app app/tmp /config/caddy /data/caddy
USER app
ENV APP_ENV=prod SERVER_NAME=:8080
EXPOSE 8080docker build -f Dockerfile.prod -t my-app .
docker run -p 8080:8080 -e APP_SECRET_KEY=... my-appThe skeleton's .dockerignore keeps vendor/ and .env out of the build. The skeleton's GET /health answers with JSON and suits a container or load balancer health check. Terminate TLS at your load balancer (and list it in trusted_proxies), or give SERVER_NAME your domain and let FrankenPHP obtain a certificate.