# Deployment

## 1. From Development to Production

The app works on `localhost:7145`. Now it needs to run around the clock on a real server. Handle thousands of concurrent users. Survive restarts. Hold steady on memory. The gap between "works on my machine" and "works in production" is where projects stumble.

This chapter covers everything for a production deployment: environment configuration, Docker packaging, web server setup, SSL/TLS, scaling, monitoring, and graceful shutdown.

When you run `tina4 init`, the framework generates a production-ready `Dockerfile` and `.dockerignore` in your project root. The Dockerfile uses a multi-stage build: the first stage installs Composer dependencies and the second stage copies only the runtime artifacts into a slim image. You do not need to write a Dockerfile from scratch -- the generated one is a solid starting point that you can customise as needed.

---

## 2. Production .env Configuration

Development defaults optimize for debugging. Production defaults optimize for performance and security. The first deployment step: configure `.env` for production.

Create a production `.env`:

```bash
# Core
TINA4_DEBUG=false
TINA4_LOG_LEVEL=WARNING
TINA4_PORT=7145

# Database
TINA4_DATABASE_URL=sqlite:///data/app.db

# Security
TINA4_CORS_ORIGINS=https://yourdomain.com
TINA4_SECRET=your-long-random-secret-at-least-32-characters
TINA4_RATE_LIMIT=120

# Performance
TINA4_TEMPLATE_CACHE_TTL=true

```

`TINA4_RATE_LIMIT` switches the rate limiter on; without it there is none. Under php-fpm the counts live in the shared cache (`TINA4_CACHE_BACKEND=redis`, `valkey` or `memcached`) or in small files under `data/ratelimit/`, so every worker sees them. A value that isn't a positive whole number makes every request answer 500, so check it before you deploy.

### Key Differences from Development

| Setting | Development | Production | Why |
|---------|------------|------------|-----|
| `TINA4_DEBUG` | `true` | `false` | Hides stack traces, disables toolbar |
| `TINA4_LOG_LEVEL` | `ALL` | `WARNING` | Reduces log noise |
| `TINA4_CORS_ORIGINS` | Your dev front end (for example `http://localhost:3000`), or empty | Your domain | Only listed origins can call the API from a browser |

### Sensitive Values

Production secrets never go into version control. The `.env` file is gitignored by default. For deployment, use environment variables from your hosting platform, CI/CD secrets, or a secrets manager.

```bash
# Docker: pass env vars at runtime
docker run -e TINA4_SECRET=your-secret -e TINA4_DATABASE_URL=sqlite:///data/app.db my-app

# Fly.io: set secrets
fly secrets set TINA4_SECRET=your-secret

# Railway: use the dashboard or CLI
railway variables set TINA4_SECRET=your-secret
```

---

## 3. FrankenPHP Auto-Detection

Tina4 PHP auto-detects FrankenPHP at startup. FrankenPHP is a modern PHP application server built on Caddy:

- Worker mode (keeps PHP in memory between requests)
- Built-in HTTPS with automatic certificate management
- HTTP/2 and HTTP/3 support
- Dramatically better performance than PHP-FPM for long-running applications

### How Auto-Detection Works

When you run `tina4 serve --production`, the CLI checks for FrankenPHP:

1. If `frankenphp` is in your PATH, it uses FrankenPHP in worker mode
2. If not, it falls back to PHP's built-in server with production optimizations

```bash
# With FrankenPHP installed
tina4 serve --production
```

```
  Tina4 PHP v3.0.0
  Server: FrankenPHP (worker mode)
  Workers: 4
  Running at https://0.0.0.0:7145
  TLS: automatic (Let's Encrypt)
```

```bash
# Without FrankenPHP
tina4 serve --production
```

```
  Tina4 PHP v3.0.0
  Server: PHP built-in
  Running at http://0.0.0.0:7145
  Warning: For production, consider FrankenPHP or PHP-FPM + nginx
```

### Installing FrankenPHP

```bash
# macOS
brew install dunglas/tap/frankenphp

# Linux
curl -fsSL https://frankenphp.dev/install.sh | bash

# Docker (no installation needed)
docker pull dunglas/frankenphp
```

---

## 4. Docker Deployment

Docker is the most portable deployment path. Your app runs the same way on your laptop, in CI, and on the production server.

### Choosing a Runtime

PHP is the one Tina4 language where the process model is a deployment decision rather than a fixed property of the runtime. `tina4 deploy docker` writes a different image for each choice:

```bash
tina4 deploy docker                     # cli (default)
tina4 deploy docker --runtime fpm       # nginx + php-fpm
tina4 deploy docker --runtime swoole    # openswoole
```

| Runtime | Server | Pick it when |
|---|---|---|
| `cli` (default) | The framework's own server | You want one image, no extra moving parts. Since 3.13.95 it forks per request, so a slow handler no longer blocks the rest. |
| `fpm` | nginx in front of php-fpm | You want the boring, safe option. Every request gets fresh process state, so nothing leaks between requests and a fatal cannot poison the next one. This is what most PHP hosting already runs. |
| `swoole` | openswoole | You are serving an API and per-request bootstrap is your bottleneck. The app stays resident, so there is no rebuild per request, plus coroutines and long-lived connections. |

Each runtime writes its own companion files, because the generated Dockerfile copies them. The `swoole` image adds `server.php`, the `fpm` image adds `nginx.fpm.conf` and `docker-entrypoint.fpm.sh`. Generate, read them, then commit them with your app.

The flag applies to PHP only. Ask for it on a Python, Ruby or Node project and the CLI refuses rather than quietly writing the default image.

### Swoole: What Changes About Your Code

Swoole keeps your application resident between requests, and that one fact is the whole trade. Anything you write to a static or a global lives for the life of the **worker**, not the request. A cache you never bound is a memory leak that grows all day.

Three rules follow:

- Keep `TINA4_DEBUG=false`. The dev toolbar keeps its message log and request inspector in static arrays that only ever grow, so a debug-mode Swoole worker climbs until something kills it. The generated image pins this for you.
- Bound anything you cache in a static yourself. Nothing else will.
- Leave `max_request` alone unless you have a reason. It recycles a worker after a set number of requests, which caps the damage from a leak you have not found yet.

If none of that appeals, the `cli` or `fpm` images cannot leak between requests, because they do not keep anything between requests.

`App::__invoke()` is the seam that makes this work. It takes a Swoole request and returns a Tina4 response, so your routes, ORM, middleware and templates are untouched. Only the transport changes.

### Official Base Image

Tina4 PHP provides an official Docker Hub base image: `tina4stack/tina4-php:v3`. It is an Alpine-based image (~140MB on disk) with PHP 8.6 (non-thread-safe build), SQLite, OPcache, and the Tina4 framework pre-installed. Your app Dockerfile extends it and adds only your application code and Composer dependencies.

The base image includes these environment variables pre-configured:
- `TINA4_OVERRIDE_CLIENT=true`, bypasses the CLI guard for Docker
- `TINA4_DEBUG=false`, production mode by default

OPcache is pre-configured with production settings (timestamps disabled, 10000 accelerated files).

### Dockerfile

Create `Dockerfile` at the project root:

```dockerfile
FROM tina4stack/tina4-php:v3
WORKDIR /app

# Install Composer and app dependencies
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./
RUN composer install --no-dev --optimize-autoloader --no-scripts \
    && rm /usr/bin/composer

# Copy application code
COPY index.php .
COPY .env .
COPY migrations/ migrations/
COPY src/ src/

# Create data directories for SQLite, sessions, queue, and mailbox
RUN mkdir -p data data/sessions data/queue data/mailbox

EXPOSE 7145
CMD ["php", "index.php", "0.0.0.0:7145"]
```

### .dockerignore

Create `.dockerignore` to keep the image small:

```
.git
.env.development
data/
logs/
secrets/
node_modules/
vendor/
tests/
.DS_Store
.tina4/
```

### Build and Run

```bash
# Build the image
docker build -t my-tina4-app .

# Run it
docker run -d \
  --name my-app \
  -p 7145:7145 \
  -e TINA4_SECRET=your-production-secret \
  -v $(pwd)/data:/app/data \
  my-tina4-app
```

### Verify

```bash
curl http://localhost:7145/health
```

```json
{"status": "ok", "uptime": 5.02, "framework": "tina4-php"}
```

That is the production body. The release version appears only with `TINA4_DEBUG=true` (see
section 6).

### Adding Database Drivers

The base image ships with SQLite only. To use PostgreSQL, MySQL, MSSQL, or Firebird, install the driver in your Dockerfile using the `install-php-extensions` tool from `mlocati`.

**PostgreSQL:**

```dockerfile
FROM tina4stack/tina4-php:v3
WORKDIR /app
COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/bin/
RUN install-php-extensions pdo_pgsql && rm /usr/bin/install-php-extensions
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./
RUN composer install --no-dev --optimize-autoloader --no-scripts && rm /usr/bin/composer
COPY index.php .
COPY .env .
COPY migrations/ migrations/
COPY src/ src/
RUN mkdir -p data data/sessions data/queue data/mailbox
EXPOSE 7145
CMD ["php", "index.php", "0.0.0.0:7145"]
```

**MySQL:**

```dockerfile
FROM tina4stack/tina4-php:v3
WORKDIR /app
COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/bin/
RUN install-php-extensions pdo_mysql && rm /usr/bin/install-php-extensions
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./
RUN composer install --no-dev --optimize-autoloader --no-scripts && rm /usr/bin/composer
COPY index.php .
COPY .env .
COPY migrations/ migrations/
COPY src/ src/
RUN mkdir -p data data/sessions data/queue data/mailbox
EXPOSE 7145
CMD ["php", "index.php", "0.0.0.0:7145"]
```

**MSSQL:**

```dockerfile
FROM tina4stack/tina4-php:v3
WORKDIR /app
COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/bin/
RUN install-php-extensions pdo_sqlsrv && rm /usr/bin/install-php-extensions
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./
RUN composer install --no-dev --optimize-autoloader --no-scripts && rm /usr/bin/composer
COPY index.php .
COPY .env .
COPY migrations/ migrations/
COPY src/ src/
RUN mkdir -p data data/sessions data/queue data/mailbox
EXPOSE 7145
CMD ["php", "index.php", "0.0.0.0:7145"]
```

**Firebird:**

Firebird requires system-level libraries not available in Alpine. Use a Debian-based PHP image instead:

```dockerfile
FROM php:8.4-cli-bookworm
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
    firebird-dev libfbclient2 && \
    docker-php-ext-install pdo_firebird interbase && \
    apt-get purge -y firebird-dev && apt-get autoremove -y && \
    rm -rf /var/lib/apt/lists/*
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./
RUN composer install --no-dev --optimize-autoloader --no-scripts && rm /usr/bin/composer
COPY index.php .
COPY .env .
COPY migrations/ migrations/
COPY src/ src/
RUN mkdir -p data data/sessions data/queue data/mailbox
EXPOSE 7145
ENV TINA4_OVERRIDE_CLIENT=true
ENV TINA4_DEBUG=false
CMD ["php", "index.php", "0.0.0.0:7145"]
```

> **Note:** The Firebird Dockerfile cannot use `tina4stack/tina4-php:v3` because the base image is Alpine and Firebird's `fbclient` library requires glibc (Debian).

### Docker Compose

Create `docker-compose.yml`:

```yaml
services:
  app:
    build: .
    ports:
      - "7145:7145"
    environment:
      - TINA4_DEBUG=false
      - TINA4_LOG_LEVEL=WARNING
      - TINA4_SECRET=${TINA4_SECRET}
      - TINA4_DATABASE_URL=sqlite:///data/app.db
    volumes:
      - app-data:/app/data
    restart: unless-stopped

volumes:
  app-data:
```

```bash
# Start everything
docker compose up -d

# View logs
docker compose logs -f app

# Stop everything
docker compose down
```

---

## 5. PHP-FPM + nginx Configuration

If you prefer a traditional setup without Docker, use PHP-FPM with nginx.

### PHP-FPM Pool Configuration

Create `/etc/php/8.3/fpm/pool.d/tina4.conf`:

```ini
[tina4]
user = www-data
group = www-data
listen = /run/php/tina4.sock
listen.owner = www-data
listen.group = www-data

pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 1000

env[TINA4_DATABASE_URL] = sqlite:///var/www/tina4-app/data/app.db
env[TINA4_SECRET] = your-production-secret
env[TINA4_DEBUG] = false
env[TINA4_LOG_LEVEL] = WARNING
```

### nginx Configuration

Create `/etc/nginx/sites-available/tina4`:

```nginx
server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/tina4-app/src/public;
    index index.php;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # Static files
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        try_files $uri =404;
    }

    # All other requests go to Tina4
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP processing
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/tina4.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
    }

    # Block access to sensitive files
    location ~ /\.(env|git|htaccess) {
        deny all;
    }

    location ~ ^/(data|logs|secrets|vendor)/ {
        deny all;
    }
}
```

Enable the site and restart:

```bash
sudo ln -s /etc/nginx/sites-available/tina4 /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
sudo systemctl restart php8.3-fpm
```

---

## 6. Health Check Endpoint

Tina4 registers a liveness endpoint for you, so there is no route to write. It answers at
`/__health` (move it with `TINA4_HEALTH_PATH`) and always at `/health` as well, so a probe
written for either path keeps working.

```bash
curl http://localhost:7145/health
```

In production (`TINA4_DEBUG=false`) the body is exactly:

```json
{"status": "ok", "uptime": 3600.25, "framework": "tina4-php"}
```

With `TINA4_DEBUG=true` it also carries `"version"`, the exact framework release. Production
leaves it out because a version string only helps an attacker match your instance to published
vulnerabilities. To check which release a container runs, ask the framework inside it (`my-app`
is the container name):

```bash
docker exec my-app php -r 'require "vendor/autoload.php"; echo \Tina4\App::$VERSION, PHP_EOL;'
```

It is a **liveness** probe. It answers `200` whenever the process can serve and checks no
database, cache or queue. That is deliberate: a failing liveness probe restarts the container,
and a restart cannot fix a database outage. Docker, Kubernetes and load balancers read only the
status code, never the body.

Use it for:

- **Docker `HEALTHCHECK`** and Compose `healthcheck:`
- **Kubernetes liveness probes**
- **Load balancer health checks** (AWS ALB, nginx upstream, HAProxy)
- **Uptime monitors** (Uptime Robot, Pingdom, custom scripts)

### A Readiness Route of Your Own

A built-in readiness endpoint is not shipped yet. When you want traffic withdrawn while a
dependency is down, add your own route on a separate path and point readiness probes at it:

```php
<?php
use Tina4\Router;
use Tina4\Database\Database;

Router::get("/ready", function ($request, $response) {
    try {
        Database::getConnection()->fetchOne("SELECT 1");
        return $response->json(["status" => "ok"]);
    } catch (\Throwable $e) {
        return $response->json(["status" => "unavailable", "database" => "disconnected"], 503);
    }
});
```

It answers `503` while the database is unreachable, so the load balancer stops routing to the
instance without restarting it. Keep the version out of this body as well.

---

## 7. Graceful Shutdown

Deploy a new version. The old process must stop. Graceful shutdown finishes active requests before terminating.

Tina4 handles this when it receives a `SIGTERM` signal (the standard shutdown signal from Docker and systemd):

1. Stop accepting new connections
2. Wait for active requests to complete (up to a configurable timeout)
3. Close database connections
4. Flush logs
5. Exit

### Shutdown Timeout

Set the maximum time to wait for in-flight requests in `.env`:

```bash
TINA4_SHUTDOWN_TIMEOUT=30
```

If requests are still processing after 30 seconds, the server force-kills them and exits. The default is 30 seconds, which is enough for most applications.

### Docker Stop Behavior

Docker sends SIGTERM, waits 10 seconds (by default), then sends SIGKILL. Match the Docker timeout to your shutdown timeout:

```yaml
services:
  app:
    stop_grace_period: 35s   # Slightly more than TINA4_SHUTDOWN_TIMEOUT
```

---

## 8. Log Rotation

In production, log files grow without limit unless rotated. Tina4 writes to `logs/app.log`.

### Using logrotate (Linux)

Create `/etc/logrotate.d/tina4`:

```
/var/www/tina4-app/logs/*.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    create 640 www-data www-data
    postrotate
        # Tina4 re-opens log files automatically
    endscript
}
```

This rotates logs daily, keeps 14 days of compressed history, and creates new log files with the correct permissions.

### Docker Logging

In Docker, application logs go to stdout/stderr by default. Configure Docker's logging driver to manage rotation:

```yaml
services:
  app:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "5"
```

This keeps a maximum of 50MB of logs (5 files of 10MB each).

---

## 9. Environment-Specific Configuration

Use different `.env` files for different environments:

```
.env                    # Development (gitignored)
.env.example            # Template (committed to git)
.env.staging            # Staging config (gitignored)
.env.production         # Production config (gitignored)
```

### Loading a Specific .env File

Set the `TINA4_ENV_FILE` environment variable before starting:

```bash
# Staging
TINA4_ENV_FILE=.env.staging tina4 serve

# Production
TINA4_ENV_FILE=.env.production tina4 serve --production
```

In Docker, pass environment variables directly:

```bash
docker run -e TINA4_DEBUG=false -e TINA4_SECRET="$TINA4_SECRET" my-app
```

Environment variables set via `docker run -e` or `docker-compose environment:` take precedence over `.env` file values. This lets you use a generic `.env` file in the image and override specific values at runtime.

---

## 10. SSL/TLS with Let's Encrypt

### With FrankenPHP (Automatic)

FrankenPHP handles SSL automatically. Just set your domain:

```bash
TINA4_HOST=yourdomain.com
```

FrankenPHP uses Let's Encrypt to provision and renew certificates automatically. No manual configuration needed.

### With nginx (Manual)

Install Certbot:

```bash
sudo apt install certbot python3-certbot-nginx
```

Obtain a certificate:

```bash
sudo certbot --nginx -d yourdomain.com
```

Certbot modifies your nginx configuration to include SSL settings and sets up automatic renewal. Verify auto-renewal:

```bash
sudo certbot renew --dry-run
```

### With Docker (Using a Reverse Proxy)

Use Traefik or Caddy as a reverse proxy in front of your Tina4 container:

```yaml
version: "3.8"

services:
  reverse-proxy:
    image: traefik:v3.0
    command:
      - "--providers.docker=true"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      - "--certificatesresolvers.letsencrypt.acme.tlschallenge=true"
      - "--certificatesresolvers.letsencrypt.acme.email=you@example.com"
      - "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - letsencrypt:/letsencrypt

  app:
    build: .
    labels:
      - "traefik.http.routers.app.rule=Host(`yourdomain.com`)"
      - "traefik.http.routers.app.tls=true"
      - "traefik.http.routers.app.tls.certresolver=letsencrypt"
    environment:
      - TINA4_DEBUG=false
      - TINA4_SECRET=${TINA4_SECRET}

volumes:
  letsencrypt:
```

---

## 11. Scaling

### Multiple Workers

FrankenPHP runs multiple worker threads by default. Configure the count in `.env`:

```bash
```

A good starting point is the number of CPU cores on your server. For I/O-heavy applications (database queries, API calls), you can go higher -- 2x to 4x the core count.

### Load Balancing with nginx

If you run multiple Tina4 instances, use nginx as a load balancer:

```nginx
upstream tina4_backend {
    server 127.0.0.1:7145;
    server 127.0.0.1:7145;
    server 127.0.0.1:7147;
    server 127.0.0.1:7148;
}

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://tina4_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

Tina4 believes those forwarded headers only from a peer listed in `TINA4_TRUSTED_PROXIES`. List the proxy, and the client's real address reaches `$request->ip` and the rate limiter, while `X-Forwarded-Proto: https` turns on the session cookies' `Secure` flag, HSTS and the CORS same-origin check. Leave it unset and every client behind the proxy shares one rate limit and the app sees plain HTTP (set `TINA4_SESSION_SECURE=true` to keep the cookie secure anyway):

```bash
TINA4_TRUSTED_PROXIES=127.0.0.1
```

Start four instances on different ports:

```bash
TINA4_PORT=7145 tina4 serve --production &
TINA4_PORT=7145 tina4 serve --production &
TINA4_PORT=7147 tina4 serve --production &
TINA4_PORT=7148 tina4 serve --production &
```

### Docker Scaling

With Docker Compose, scale horizontally:

```bash
docker compose up -d --scale app=4
```

Use a load balancer (Traefik, nginx, or a cloud load balancer) in front of the containers.

---

## 12. Monitoring

### Log Aggregation

In production, send logs to a centralized service:

```bash
TINA4_LOG_FORMAT=json
```

JSON-formatted logs can be ingested by services like:

- Elastic Stack (ELK)
- Grafana Loki
- Datadog
- AWS CloudWatch

Example JSON log entry:

```json
{
  "timestamp": "2026-03-22T14:30:00.123Z",
  "level": "WARNING",
  "message": "Rate limit exceeded",
  "request_id": "req-abc123",
  "ip": "203.0.113.42",
  "path": "/api/products",
  "method": "GET"
}
```

### Uptime Monitoring

Point an external monitoring service at your health endpoint:

```
https://yourdomain.com/health
```

Services like Uptime Robot, Pingdom, or Better Uptime will ping this endpoint every 30-60 seconds and alert you if it stops responding or returns a non-200 status.

### Application Performance Monitoring (APM)

For deeper insights, add APM instrumentation. Since Tina4 is standard PHP, any PHP APM agent works:

- New Relic APM
- Datadog APM
- Elastic APM

These agents track request latency, database query performance, error rates, and memory usage automatically.

---

## 13. Exercise: Deploy a Tina4 PHP App with Docker

Deploy the task management application you have been building throughout this book.

### Requirements

1. Create a `Dockerfile` that:
   - Uses `tina4stack/tina4-php:v3` as the base image
   - Installs Composer dependencies
   - Copies the application code
   - Creates data directories
   - Exposes port 7145

2. Create a `docker-compose.yml` that:
   - Builds and runs the application
   - Maps port 7145
   - Uses environment variables for secrets
   - Persists the database via volumes
   - Includes restart policy

3. Create a production `.env.production` with:
   - Debug mode off
   - Warning-level logging
   - Template caching enabled
   - Appropriate CORS settings

4. Build and run the container.

5. Verify the health check works.

6. Verify you can create and list products through the containerized API.

### Test with:

```bash
# Build
docker compose build

# Start
docker compose up -d

# Health check
curl http://localhost:7145/health

# Create a product
curl -X POST http://localhost:7145/api/products \
  -H "Content-Type: application/json" \
  -d '{"name": "Docker Widget", "price": 19.99}'

# List products
curl http://localhost:7145/api/products

# View logs
docker compose logs app

# Stop
docker compose down
```

---

## 14. Solution

### Dockerfile

```dockerfile
FROM tina4stack/tina4-php:v3
WORKDIR /app

COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock* ./
RUN composer install --no-dev --optimize-autoloader --no-scripts \
    && rm /usr/bin/composer

COPY index.php .
COPY .env .
COPY migrations/ migrations/
COPY src/ src/

RUN mkdir -p data data/sessions data/queue data/mailbox

EXPOSE 7145
CMD ["php", "index.php", "0.0.0.0:7145"]
```

### docker-compose.yml

```yaml
services:
  app:
    build: .
    ports:
      - "7145:7145"
    environment:
      - TINA4_DEBUG=false
      - TINA4_LOG_LEVEL=WARNING
      - TINA4_TEMPLATE_CACHE_TTL=true
      - TINA4_SECRET=replace-with-the-output-of-openssl-rand-hex-32
      - TINA4_DATABASE_URL=sqlite:///data/app.db
      - TINA4_CORS_ORIGINS=http://localhost:7145
    volumes:
      - app-data:/app/data
    restart: unless-stopped
    stop_grace_period: 35s

volumes:
  app-data:
```

### .env.production

```bash
TINA4_DEBUG=false
TINA4_LOG_LEVEL=WARNING
TINA4_TEMPLATE_CACHE_TTL=true
TINA4_RATE_LIMIT=120
TINA4_CORS_ORIGINS=https://yourdomain.com
```

**Expected output for health check:**

```json
{"status": "ok", "uptime": 8.31, "framework": "tina4-php"}
```

**Expected output for creating a product:**

```json
{
  "id": 1,
  "name": "Docker Widget",
  "price": 19.99,
  "in_stock": true,
  "created_at": "2026-03-22 14:30:00",
  "updated_at": "2026-03-22 14:30:00"
}
```

---

## 15. Gotchas

### 1. SQLite Concurrency in Production

**Problem:** Under high load, SQLite throws "database is locked" errors.

**Cause:** SQLite uses file-level locking. Multiple concurrent writes block each other.

**Fix:** For low-to-medium traffic (under 100 concurrent users), SQLite works fine. For higher traffic, switch to PostgreSQL or MySQL:

```bash
TINA4_DATABASE_URL=postgres://user:pass@localhost:5432/myapp
```

If you must use SQLite under load, enable WAL mode by adding this to your application startup:

```php
$db = Tina4\Database\Database::getConnection();
$db->exec("PRAGMA journal_mode=WAL");
```

### 2. Data Volume Not Persisted

**Problem:** You restart the Docker container and the database is empty.

**Cause:** The `data/` directory is inside the container. When the container is recreated, the data is lost.

**Fix:** Use a Docker volume to persist the data directory, as shown in the docker-compose.yml above:

```yaml
volumes:
  - app-data:/app/data
```

### 3. .env File Not Loaded in Docker

**Problem:** Environment variables from `.env` are not available in the container.

**Cause:** Docker does not automatically load `.env` files inside the container. The `.env` file is for the host machine (used by `docker compose`).

**Fix:** Pass environment variables via the `environment:` section in `docker-compose.yml`, or use `env_file:`:

```yaml
services:
  app:
    env_file:
      - .env.production
```

### 4. Permission Denied on data/ Directory

**Problem:** The application cannot write to `data/` or `logs/` inside the container.

**Cause:** The directories were created by root during the Docker build, but the application runs as `www-data`.

**Fix:** Add `chown` to your Dockerfile:

```dockerfile
RUN mkdir -p data logs secrets \
    && chown -R www-data:www-data data logs secrets
```

### 5. Health Check Fails During Startup

**Problem:** The container restarts in a loop because the health check fails before the application is ready.

**Cause:** The health check starts immediately, but the application needs a few seconds to initialize.

**Fix:** Use `start_period` in the health check to give the application time to start:

```dockerfile
HEALTHCHECK --start-period=10s --interval=30s --timeout=5s --retries=3 \
    CMD curl -f http://localhost:7145/health || exit 1
```

The `start-period` tells Docker to ignore health check failures during the first 10 seconds.

### 6. CORS Errors in Production

**Problem:** Your frontend gets "No 'Access-Control-Allow-Origin' header" errors.

**Cause:** `TINA4_CORS_ORIGINS` is set to `*` in development but to a specific domain in production. If your frontend is served from a different domain or port, CORS blocks the requests.

**Fix:** Set `TINA4_CORS_ORIGINS` to include all domains that need access:

```bash
TINA4_CORS_ORIGINS=https://yourdomain.com,https://admin.yourdomain.com
```

### 7. SSL Certificate Not Renewing

**Problem:** Your HTTPS certificate expires and the site goes down.

**Cause:** The auto-renewal process (Certbot or FrankenPHP) failed silently. Common reasons: DNS changes, firewall blocking port 80 (needed for ACME challenge), or the renewal service crashed.

**Fix:** Set up monitoring for certificate expiry. Use a tool like `ssl-cert-check` or an online service that alerts you before the certificate expires. Check renewal logs:

```bash
# Certbot
sudo certbot renew --dry-run

# Check crontab for renewal
sudo systemctl list-timers | grep certbot
```

For FrankenPHP, ensure port 80 and 443 are accessible from the internet for ACME challenges.
