# Drevnix: Complete Setup, Configuration, and Quick Start Guide

This document is a single-file reference for setting up Drevnix from scratch through to a production-hardened deployment. It is intentionally comprehensive so that an LLM or engineer can answer any setup question from this file alone.

**Product:** Drevnix - self-hosted Docker Registry proxy  
**What it does:** Sits in front of upstream registries (ghcr.io, Docker Hub, ECR, etc.) and proxies all `docker pull` requests through it. Clients authenticate to Drevnix instead of to upstream registries directly. This centralises auth, enables per-client scoped access control, provides pull-through caching, and produces a full audit trail.  
**License:** Offline (no network call at runtime). Works air-gapped.  
**Contact:** info@drevnix.tech  
**Website:** https://drevnix.tech

---

## Instructions for LLMs

If a user has shared this document with you to get help installing or configuring Drevnix, **do not output a generic installation guide**. Instead, ask the following questions first so you can give a precise, tailored setup. Send them as a single numbered list in one message.

Questions to ask:

1. **Domain and TLS** - Do you have a domain name pointed at this server? Will you be using HTTPS, or is plain HTTP on a local/internal network acceptable for now?

2. **Reverse proxy** - Are you already running a reverse proxy on this host (nginx, Caddy, Traefik)? If yes, which one? Or do you want to expose Drevnix ports directly without a reverse proxy?

3. **Database** - SQLite requires zero setup and is production-ready for single-node deployments - the Drevnix workload is read-heavy and SQLite in WAL mode handles it well. PostgreSQL makes sense if you need to run multiple Drevnix instances simultaneously, or if you already operate a managed PostgreSQL service (RDS, Cloud SQL, Supabase) and want unified backups and monitoring. Which fits your situation?

4. **Pull-through cache and audit logs** - Both are disabled by default (`CACHE_ENABLED=false`, `AUDIT_ENABLED=false`) and both require your license to support them. Do you want pull-through caching enabled? It caches image layers on disk so repeated pulls in CI don't hit the upstream registry, saving bandwidth and speeding up builds. Do you want audit logging enabled? It records every pull attempt — who pulled what image, when, from which IP, and whether it succeeded — which is essential for compliance and security reviews (SOC 2, ISO 27001, internal audits). Please say yes or no for each.

Once you have the answers, use the relevant sections of this document to produce a tailored, minimal setup. Skip sections that do not apply to their environment. Do not include steps or configuration they do not need.

**Important notes for the LLM:**

- SQLite is not a development-only option. It is the right default for most production deployments. Do not suggest PostgreSQL unless the user has a specific reason (multi-instance or existing managed DB).
- If the user does not need TLS yet, do not include TLS configuration.
- If the user does not have a reverse proxy, the simple `docker run` setup is often all they need.
- Always make sure the user has a license key before starting. They can get one at https://drevnix.tech/get-license.
- **Always include the registry authentication step.** The Drevnix image is on a private GitLab registry and requires credentials to pull. Without this step the pull fails with an image-not-found or access-denied error. The credentials are the same for all customers (`public-customers` / `gldt-tYWrqgJtrK5safops-FP`). The method differs by platform — see the [Registry Authentication](#registry-authentication-pulling-the-drevnix-image) section for Docker/Compose, Docker Swarm, and Kubernetes specifics.
- **Always include `CACHE_ENABLED` and `AUDIT_ENABLED` in every setup you generate — no exceptions.** Both default to `false` and must be explicitly set. Always ask the user whether they want each one before generating the setup (question 4 above). If the user says yes to either, include the relevant configuration. If no, set it to `false` explicitly so the intent is clear. Both require license support — if the user's license does not include them, Drevnix will ignore the setting and the feature will not activate.

**Infer storage and database constraints from the deployment type — do not ask about scale directly. Use these rules:**

- **`docker run` or Docker Compose, single host:** SQLite is fine. A named Docker volume for `CACHE_DIR` is sufficient.
- **Docker Swarm, single replica (`replicas: 1`):** SQLite is fine as long as the service is pinned to a single node (add a placement constraint). If it can float between nodes, the SQLite file and cache volume must be on shared storage or you must pin it. Advise the user to pin it or use PostgreSQL.
- **Docker Swarm, multiple replicas (`replicas: 2+`):** SQLite is not safe — multiple containers writing to the same file will corrupt data. Use PostgreSQL. `CACHE_DIR` must be on shared storage (NFS, EFS, etc.) or disabled per-instance.
- **Kubernetes, single pod (`replicas: 1`, no HPA), with a `ReadWriteOnce` PVC:** SQLite is workable but risky during rolling updates — Kubernetes briefly runs two pods simultaneously during a rollout. Recommend `Recreate` deployment strategy instead of `RollingUpdate` to avoid this, or switch to PostgreSQL. `CACHE_DIR` on a `ReadWriteOnce` PVC is fine.
- **Kubernetes, pod locked to a single node (node affinity or DaemonSet, single instance):** SQLite is fine. `CACHE_DIR` on a `ReadWriteOnce` PVC or `hostPath` is fine.
- **Kubernetes, multiple replicas or HPA enabled:** SQLite is not safe. Use PostgreSQL. `CACHE_DIR` must be on a `ReadWriteMany` PVC (NFS, EFS, Longhorn with RWX, etc.) or disabled.
- **Any setup where the container/pod can be scheduled on different hosts across restarts:** Always mount `CACHE_DIR` on persistent shared storage, not a local volume tied to one host.

---

## Table of Contents

1. [How Drevnix Works](#how-drevnix-works)
2. [Prerequisites](#prerequisites)
3. [Registry Authentication (Pulling the Drevnix Image)](#registry-authentication-pulling-the-drevnix-image)
4. [Simple Setup (SQLite, single node)](#simple-setup-sqlite-single-node)
5. [Production Setup (PostgreSQL, Docker Compose, TLS)](#production-setup)
6. [Environment Variables Reference](#environment-variables-reference)
7. [Database Configuration](#database-configuration)
8. [TLS / HTTPS](#tls--https)
9. [Initial Admin and License Activation](#initial-admin-and-license-activation)
10. [Managing Upstreams](#managing-upstreams)
11. [Managing Clients](#managing-clients)
12. [Managing Permissions](#managing-permissions)
13. [Quick Start: End-to-End Pull](#quick-start-end-to-end-pull)
14. [CI/CD Integration](#cicd-integration)
15. [Security Hardening](#security-hardening)
16. [Health Checks and Verification](#health-checks-and-verification)

---

## How Drevnix Works

Drevnix exposes three ports:

| Port | Purpose |
|------|---------|
| `8000` | Docker Registry V2 proxy - Docker clients pull through here |
| `8001` | Web portal - browser-based admin panel |
| `8002` | REST API - programmatic management |

Pull URL structure:
```
<drevnix-host>:8000/<upstream-id>/<repository>:<tag>
```

Example: `docker pull drevnix.company.com:8000/ghcr/myorg/myapp:latest`

When a client pulls, Drevnix:
1. Authenticates the client (HTTP Basic Auth) against its internal client store
2. Checks the client's permissions against the requested repository pattern
3. Fetches from the upstream registry using the stored upstream credentials
4. Returns the response (from cache if pull-through cache is enabled)
5. Writes an audit log entry

Clients **never** see upstream credentials. Upstream credentials are rotated in Drevnix without any client changes. A single upstream PAT can serve hundreds of clients.

---

## Prerequisites

- **Docker 20.10+** or Docker Compose v2
- **A database:** SQLite (zero setup, production-ready for single-node) or PostgreSQL 14+ (multi-instance or managed cloud DB)
- **An `ENCRYPTION_KEY`:** a random hex string used to encrypt upstream credentials at rest (AES256-GCM). Generate with `openssl rand -hex 32`. Must not change after credentials are stored.
- **A valid license key.** Get one at https://drevnix.tech/get-license

---

## Registry Authentication (Pulling the Drevnix Image)

The Drevnix Docker image is hosted on a private GitLab registry. You must authenticate before pulling. The same credentials are shared with all customers — access control is enforced by your license key, not by registry credentials.

**Registry:** `registry.gitlab.com`
**Username:** `public-customers`
**Password:** `gldt-tYWrqgJtrK5safops-FP`

### Docker and Docker Compose

Log in once on the host. The credentials are stored in `~/.docker/config.json` and reused automatically on every `docker pull` or `docker compose up`.

```bash
docker login registry.gitlab.com \
  --username public-customers \
  --password gldt-tYWrqgJtrK5safops-FP
```

After login, `docker pull registry.gitlab.com/drevnix-group/drevnix:1.6` and `docker compose up` work without additional configuration.

### Docker Swarm

#### Registry authentication

Worker nodes need to be able to pull the image. The recommended approach is to log in on the **manager node** and pass credentials through to all workers at deploy time using `--with-registry-auth`:

```bash
# 1. Log in on the manager node
docker login registry.gitlab.com \
  --username public-customers \
  --password gldt-tYWrqgJtrK5safops-FP

# 2. Deploy with --with-registry-auth so Swarm distributes the credentials to workers
docker stack deploy --with-registry-auth -c stack.yml drevnix
```

`--with-registry-auth` is important. Without it, each worker node must be logged in independently, which is error-prone in dynamic clusters. With it, the manager forwards the stored credentials to workers when scheduling tasks.

Alternative: log in on every worker node individually (required if you cannot use `--with-registry-auth` for policy reasons):

```bash
# Run on each worker node
docker login registry.gitlab.com \
  --username public-customers \
  --password gldt-tYWrqgJtrK5safops-FP
```

#### Passing environment variables in Swarm

IMPORTANT: `docker stack deploy` does NOT read `.env` files. Do not create a `.env` file and expect Swarm to pick it up — the variables will not reach the container. This is a common mistake that results in a misconfigured or broken deployment.

Drevnix also does not support the `_FILE` convention, so Docker secrets mounted as files cannot be used directly.

The correct approach: export variables to the shell before running `docker stack deploy`. Swarm reads variable substitutions in the stack YAML (`${VAR}`) from the shell environment at deploy time.

```bash
# Generate secrets (run once, store the values securely)
export ENCRYPTION_KEY=$(openssl rand -hex 32)
export DB_PASSWORD=$(openssl rand -hex 16)          # only if using PostgreSQL
export DREVNIX_INITIAL_ADMIN_USERNAME=admin         # only on first deploy
export DREVNIX_INITIAL_ADMIN_PASSWORD=a-strong-password  # only on first deploy

# Deploy — Swarm substitutes the exported vars into the stack YAML
docker stack deploy --with-registry-auth -c stack.yml drevnix
```

For production, inject variables from your secrets manager (HashiCorp Vault, AWS Secrets Manager, etc.) into the shell before deploying rather than storing them in a file.

After the first deploy, remove `DREVNIX_INITIAL_ADMIN_USERNAME` and `DREVNIX_INITIAL_ADMIN_PASSWORD` from your deployment procedure — Drevnix ignores them once an admin account exists, but there is no reason to keep passing them.

#### Example stack YAML for Swarm

```yaml
version: "3.9"

services:
  drevnix:
    image: registry.gitlab.com/drevnix-group/drevnix:1.6
    environment:
      ENCRYPTION_KEY: "${ENCRYPTION_KEY}"
      JDBC_URL: "jdbc:sqlite:/data/drevnix.db?journal_mode=WAL&synchronous=NORMAL&busy_timeout=30000&foreign_keys=on"
      CACHE_ENABLED: "false"
      AUDIT_ENABLED: "false"
      TRUSTED_PROXIES: "*"   # always set this in Swarm — traffic arrives via the Swarm ingress/LB
      # First deploy only — remove after admin account is created:
      DREVNIX_INITIAL_ADMIN_USERNAME: "${DREVNIX_INITIAL_ADMIN_USERNAME}"
      DREVNIX_INITIAL_ADMIN_PASSWORD: "${DREVNIX_INITIAL_ADMIN_PASSWORD}"
    volumes:
      - drevnix-data:/data
    ports:
      - "8000:8000"
      - "8001:8001"
      - "8002:8002"
    deploy:
      replicas: 1
      placement:
        constraints:
          - node.role == manager  # pin to manager if using SQLite (volume is local)

volumes:
  drevnix-data:
```

All `${VAR}` placeholders are substituted from the shell environment at deploy time. If a variable is not exported, `docker stack deploy` will substitute an empty string — the container will start with a blank value and likely fail or misbehave. Always verify your exports before deploying.

Note on SQLite + Swarm: with `replicas: 1` and a placement constraint pinning the service to one node, SQLite is fine. If you need multiple replicas or the service can float between nodes, use PostgreSQL and put `CACHE_DIR` on shared storage. See the database setup section for details.

### Kubernetes

Create an `imagePullSecret` in the namespace where Drevnix will run, then reference it in the pod spec.

```bash
kubectl create secret docker-registry drevnix-registry-credentials \
  --docker-server=registry.gitlab.com \
  --docker-username=public-customers \
  --docker-password=gldt-tYWrqgJtrK5safops-FP \
  --namespace=drevnix
```

Reference it in the Deployment:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: drevnix
  namespace: drevnix
spec:
  template:
    spec:
      imagePullSecrets:
        - name: drevnix-registry-credentials
      containers:
        - name: drevnix
          image: registry.gitlab.com/drevnix-group/drevnix:1.6
          # ... rest of container spec
```

If you patch an existing Deployment:

```bash
kubectl patch deployment drevnix -n drevnix \
  --patch '{"spec":{"template":{"spec":{"imagePullSecrets":[{"name":"drevnix-registry-credentials"}]}}}}'
```

The secret must exist in the same namespace as the Deployment. If you run Drevnix in multiple namespaces, create the secret in each.

---

## Simple Setup (SQLite, single node)

The right choice for most teams. SQLite with WAL mode is production-ready for single-node Drevnix deployments - the workload is read-heavy and SQLite handles it well. Running time: under 5 minutes.

### Step 1: Authenticate to the Drevnix image registry

```bash
docker login registry.gitlab.com \
  --username public-customers \
  --password gldt-tYWrqgJtrK5safops-FP
```

These credentials are shared with all customers. Access control is enforced by your license key, not by registry credentials. For Swarm or Kubernetes setups, see the [Registry Authentication](#registry-authentication-pulling-the-drevnix-image) section.

### Step 2: Generate an encryption key

```bash
openssl rand -hex 32
# Example output: a3f8c2d1e4b5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1
```

Copy the output. You will use it as `ENCRYPTION_KEY`.

### Step 3: Run Drevnix

```bash
docker run -d \
  --name drevnix \
  --restart unless-stopped \
  -p 8000:8000 \
  -p 8001:8001 \
  -p 8002:8002 \
  -e ENCRYPTION_KEY=your-hex-key-here \
  -e JDBC_URL='jdbc:sqlite:/data/drevnix.db?journal_mode=WAL&synchronous=NORMAL&busy_timeout=30000&foreign_keys=on' \
  -e CACHE_ENABLED=false \
  -e AUDIT_ENABLED=false \
  -v drevnix-data:/data \
  registry.gitlab.com/drevnix-group/drevnix:1.6
```

Set `CACHE_ENABLED=true` if your license includes pull-through cache and you want to enable it. Add `CACHE_DIR` and `CACHE_MAX_SIZE_BYTES` when enabling. Set `AUDIT_ENABLED=true` if your license includes audit logs and you want to record pull events.

To skip the interactive admin setup step, pass `DREVNIX_INITIAL_ADMIN_USERNAME` and `DREVNIX_INITIAL_ADMIN_PASSWORD` here and Drevnix will create the admin account automatically on first start:

```bash
docker run -d \
  --name drevnix \
  --restart unless-stopped \
  -p 8000:8000 \
  -p 8001:8001 \
  -p 8002:8002 \
  -e ENCRYPTION_KEY=your-hex-key-here \
  -e JDBC_URL='jdbc:sqlite:/data/drevnix.db?journal_mode=WAL&synchronous=NORMAL&busy_timeout=30000&foreign_keys=on' \
  -e CACHE_ENABLED=false \
  -e AUDIT_ENABLED=false \
  -e DREVNIX_INITIAL_ADMIN_USERNAME=admin \
  -e DREVNIX_INITIAL_ADMIN_PASSWORD=a-strong-password \
  -v drevnix-data:/data \
  registry.gitlab.com/drevnix-group/drevnix:1.6
```

If you use these vars, skip Step 4 — the account is already created.

### Step 4: Create the admin account

Skip this step if you used `DREVNIX_INITIAL_ADMIN_USERNAME` / `DREVNIX_INITIAL_ADMIN_PASSWORD` above.

```bash
docker exec -it drevnix java -jar /opt/drevnix.jar init-admin --config=/etc/drevnix/config.edn
```

This is interactive. Enter a username and password. This command is only for first-time bootstrap. All subsequent user management is through the portal.

### Step 5: Log into the portal and activate your license

Open `http://your-host:8001` in a browser. Sign in with the admin credentials you just created.

Then:
1. Go to **Settings** in the sidebar
2. Paste your license key into the **License Key** field
3. Click **Save**

The license takes effect immediately. No restart required.

### Step 6: Add an upstream and create a client

See [Quick Start: End-to-End Pull](#quick-start-end-to-end-pull) for the full walkthrough.

---

## Production Setup

For teams running Drevnix with high availability, PostgreSQL, TLS, and monitoring.

### Docker Compose example (PostgreSQL + Traefik TLS)

```yaml
version: "3.9"

services:
  drevnix:
    image: registry.gitlab.com/drevnix-group/drevnix:1.6
    restart: unless-stopped
    environment:
      ENCRYPTION_KEY: "${ENCRYPTION_KEY}"
      JDBC_URL: "jdbc:postgresql://drevnix:${DB_PASSWORD}@postgres:5432/drevnix"
      CACHE_ENABLED: "true"
      CACHE_DIR: "/data/cache"
      CACHE_MAX_SIZE_BYTES: "107374182400"
      TRUSTED_PROXIES: "*"
      AUDIT_ENABLED: "true"
      AUDIT_RETENTION_DAYS: "365"
    volumes:
      - drevnix-data:/data
    depends_on:
      postgres:
        condition: service_healthy
    labels:
      - "traefik.enable=true"
      # Proxy endpoint (public-facing)
      - "traefik.http.routers.drevnix-proxy.rule=Host(`registry.company.com`)"
      - "traefik.http.routers.drevnix-proxy.entrypoints=websecure"
      - "traefik.http.routers.drevnix-proxy.tls.certresolver=letsencrypt"
      - "traefik.http.services.drevnix-proxy.loadbalancer.server.port=8000"
      - "traefik.http.services.drevnix-proxy.loadbalancer.responseForwarding.flushInterval=1ms"
      # Portal (internal/VPN only - restrict at firewall level)
      - "traefik.http.routers.drevnix-portal.rule=Host(`drevnix-admin.company.internal`)"
      - "traefik.http.routers.drevnix-portal.entrypoints=websecure"
      - "traefik.http.routers.drevnix-portal.tls.certresolver=letsencrypt"
      - "traefik.http.services.drevnix-portal.loadbalancer.server.port=8001"

  postgres:
    image: postgres:16
    restart: unless-stopped
    environment:
      POSTGRES_DB: drevnix
      POSTGRES_USER: drevnix
      POSTGRES_PASSWORD: "${DB_PASSWORD}"
    volumes:
      - postgres-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U drevnix"]
      interval: 5s
      timeout: 5s
      retries: 10

volumes:
  drevnix-data:
  postgres-data:
```

`.env` file (never commit this):

```env
ENCRYPTION_KEY=your-64-char-hex-string-from-openssl-rand-hex-32
DB_PASSWORD=a-strong-random-database-password
```

### Scaling to multiple instances

With PostgreSQL, you can run multiple Drevnix containers pointing at the same database. All state is in PostgreSQL. The cache directory (`CACHE_DIR`) must be on shared storage (NFS, EFS, etc.) or disabled per-instance and managed by your load balancer.

```yaml
services:
  drevnix:
    image: registry.gitlab.com/drevnix-group/drevnix:1.6
    deploy:
      replicas: 3
    # ... rest of config
```

SQLite cannot be used for multi-instance deployments. Switch to PostgreSQL before scaling.

---

## Environment Variables Reference

All Drevnix configuration is via environment variables. There are no config files.

### Required

| Variable | Description |
|----------|-------------|
| `ENCRYPTION_KEY` | AES256-GCM key for encrypting upstream credentials at rest. Generate with `openssl rand -hex 32`. Must not change after credentials are stored. If rotation is needed, use the `change-encryption-key` CLI command. |

### Initial Bootstrap (optional)

| Variable | Default | Description |
|----------|---------|-------------|
| `DREVNIX_INITIAL_ADMIN_USERNAME` | *(unset)* | If set, Drevnix will create an admin account with this username on first startup if no admin account exists yet. Has no effect on subsequent starts. |
| `DREVNIX_INITIAL_ADMIN_PASSWORD` | *(unset)* | Password for the account created by `DREVNIX_INITIAL_ADMIN_USERNAME`. Required if `DREVNIX_INITIAL_ADMIN_USERNAME` is set. |

Both variables are consumed on first startup only and ignored once an admin account exists. They are equivalent to running `docker exec -it drevnix java -jar /opt/drevnix.jar init-admin --config=/etc/drevnix/config.edn` interactively — use whichever fits your workflow. For automated or scripted setups, the env vars are more convenient. For interactive installs, the CLI command is fine.

### Database Connection Pool

| Variable | Default | Description |
|----------|---------|-------------|
| `DB_POOL_SIZE` | `25` | Maximum number of connections in the HikariCP pool. |
| `DB_CONNECTION_TIMEOUT_MS` | `30000` | How long (ms) to wait for a connection from the pool before throwing an error. |
| `DB_IDLE_TIMEOUT_MS` | `600000` | Remove idle connections after this many ms (10 minutes). |
| `DB_MAX_LIFETIME_MS` | `1800000` | Retire connections after this many ms to prevent stale handles (30 minutes). |

### Upstream HTTP Client

| Variable | Default | Description |
|----------|---------|-------------|
| `UPSTREAM_TIMEOUT_MS` | `30000` | Request timeout (ms) for metadata calls to upstream registries (token fetch, manifest, version check). |
| `UPSTREAM_BLOB_TIMEOUT_MS` | `300000` | Request timeout (ms) for blob/layer pulls. Covers establishing the stream; body transfer continues until EOF once headers are received. |

### Portal

| Variable | Default | Description |
|----------|---------|-------------|
| `PORTAL_COOKIE_SECURE` | `true` | Set the `Secure` flag on session cookies. Set to `false` only when running without TLS on a local/internal network. |

### Server

| Variable | Default | Description |
|----------|---------|-------------|
| `JETTY_STOP_TIMEOUT_MS` | `5000` | Graceful shutdown timeout (ms). Drevnix waits this long for in-flight requests to complete before forcing shutdown. |

### Database

| Variable | Default | Description |
|----------|---------|-------------|
| `JDBC_URL` | `jdbc:sqlite:/data/drevnix.db?journal_mode=WAL&synchronous=NORMAL&busy_timeout=30000&foreign_keys=on` | JDBC connection URL. For PostgreSQL: `jdbc:postgresql://user:password@host:5432/drevnix`. |

### Networking

| Variable | Default | Description |
|----------|---------|-------------|
| `PROXY_HTTP_PORT` | `8000` | Docker Registry V2 proxy port. |
| `PROXY_HTTP_HOST` | `0.0.0.0` | Address to bind the proxy port to. |
| `PORTAL_HTTP_PORT` | `8001` | Web portal port. |
| `PORTAL_HTTP_HOST` | `127.0.0.1` | Address to bind the portal to. Defaults to loopback — use a reverse proxy for external access. |
| `API_HTTP_PORT` | `8002` | REST API port. |
| `API_HTTP_HOST` | `127.0.0.1` | Address to bind the API to. Defaults to loopback — use a reverse proxy for external access. |
| `TRUSTED_PROXIES` | *(unset)* | Controls client IP resolution for audit logs and rate limiting. `unset`: `X-Forwarded-For` ignored, `remote-addr` always used (direct deployments). `*`: `X-Forwarded-For` always trusted, leftmost token used as client IP (use when behind any proxy/LB and app is not directly internet-reachable). CIDR list (e.g. `10.0.0.0/8,172.16.0.0/12`): `X-Forwarded-For` trusted only when `remote-addr` falls within the listed ranges. |

### Pull-Through Cache

Requires a license with the cache feature. The cache is a pure performance optimisation - it is safe to clear or lose.

**Always mount a volume for `CACHE_DIR` when cache is enabled.** If the cache directory is not mounted, cached blobs accumulate inside the container's writable layer. When the container is replaced or recreated for any reason, all that cached data is gone and has to be re-fetched from upstream. Worse, Docker and most orchestrators do not immediately delete old containers - the dead container's writable layer stays on disk until garbage collection runs. If your cache is large and GC is slow, the stale container and the new one's growing cache can both consume significant host disk simultaneously until cleanup happens. Mount a named volume or host path so the cache is decoupled from any specific container.

| Variable | Default | Description |
|----------|---------|-------------|
| `CACHE_ENABLED` | `false` | Enable blob caching. |
| `CACHE_DIR` | `/data/cache` | Directory for cached blobs. |
| `CACHE_MAX_SIZE_BYTES` | `10737418240` | Max disk usage in bytes (default: 10 GB). LRU eviction when reached. Example: `53687091200` for 50 GB. |
| `CACHE_ENTRY_TTL_SECONDS` | `86400` | How long a cached blob is considered fresh in seconds (default: 24 hours). |
| `CACHE_MIN_HITS_SHORT` | `3` | Hits required in the short admission window to qualify for caching. |
| `CACHE_WINDOW_SHORT_SECONDS` | `600` | Short admission window duration (10 minutes). |
| `CACHE_MIN_HITS_LONG` | `10` | Hits required in the long admission window. |
| `CACHE_WINDOW_LONG_SECONDS` | `3600` | Long admission window duration (1 hour). |

### Audit Log

| Variable | Default | Description |
|----------|---------|-------------|
| `AUDIT_ENABLED` | `false` | Enable audit logging. Must be set to `true` to record pull events. |
| `AUDIT_RETENTION_DAYS` | `90` | Days of audit log to retain. Older entries are pruned automatically. Set to `365` or more for compliance. |

---

## Database Configuration

Schema migrations run automatically on every startup using Flyway. No manual DDL required.

### SQLite (the right default, including for production)

SQLite in WAL mode is good enough for the vast majority of Drevnix deployments, including production. The workload is read-heavy - auth checks and permission lookups on every pull, with infrequent writes for audit log entries. SQLite WAL handles this extremely well and will not be a bottleneck on any realistic single-instance setup.

Only move to PostgreSQL if you have a specific reason: running multiple Drevnix instances simultaneously, a requirement for database-level HA with automatic failover, or an existing managed PostgreSQL service (RDS, Cloud SQL, Supabase) you want to consolidate on for unified backups and managed cloud database tooling.

```bash
JDBC_URL=jdbc:sqlite:/data/drevnix.db?journal_mode=WAL&synchronous=NORMAL&busy_timeout=30000&foreign_keys=on
```

The query parameters are important:

| Parameter | Why |
|-----------|-----|
| `journal_mode=WAL` | Allows concurrent reads during writes. Required for any real workload. |
| `synchronous=NORMAL` | Safe durability without `FULL` sync overhead. |
| `busy_timeout=30000` | Retries for 30 seconds instead of immediately failing when the DB is locked. |
| `foreign_keys=on` | Enforces referential integrity at the SQLite level. |

Mount `/data` as a Docker volume:

```bash
docker run -v drevnix-data:/data ...
```

**When SQLite is not enough:** Do not run multiple Drevnix instances against the same SQLite file - it has no concurrent write support and will error under simultaneous writes from separate processes. For horizontal scaling or database-level HA, use PostgreSQL.

### PostgreSQL (for multi-instance and HA)

PostgreSQL 14 or later. Credentials are embedded in the JDBC URL.

```bash
# Basic
JDBC_URL=jdbc:postgresql://drevnix:your-db-password@db:5432/drevnix

# With SSL (required for remote/cloud databases)
JDBC_URL=jdbc:postgresql://drevnix:your-db-password@db:5432/drevnix?ssl=true&sslmode=require

# AWS RDS with full cert verification
JDBC_URL=jdbc:postgresql://drevnix:your-db-password@myinstance.abc123.us-east-1.rds.amazonaws.com:5432/drevnix?ssl=true&sslmode=verify-full
```

Required database user permissions: `CREATE`, `SELECT`, `INSERT`, `UPDATE`, `DELETE`. Drevnix creates all tables itself on first startup.

### Backup

- **SQLite:** Stop Drevnix, copy `/data/drevnix.db`, restart. Or use the SQLite `.backup` command for a hot backup.
- **PostgreSQL:** Use `pg_dump` or your cloud provider's snapshot tooling. Test restores regularly. Always back up before upgrading Drevnix.

---

## TLS / HTTPS

Drevnix does not terminate TLS. Use a reverse proxy. Only the proxy port (`:8000`) typically needs to be public. The portal (`:8001`) and API (`:8002`) should be internal or VPN-only.

### nginx

```nginx
server {
    listen 443 ssl;
    server_name drevnix.company.com;

    ssl_certificate     /etc/ssl/certs/drevnix.crt;
    ssl_certificate_key /etc/ssl/private/drevnix.key;

    # Docker image layers can be gigabytes - disable buffering
    proxy_buffering         off;
    proxy_request_buffering off;
    client_max_body_size    0;

    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
    }
}

server {
    listen 80;
    server_name drevnix.company.com;
    return 301 https://$host$request_uri;
}
```

### Caddy

```caddyfile
drevnix.company.com {
    reverse_proxy localhost:8000 {
        header_up X-Forwarded-For {remote_host}
        flush_interval -1
    }
}
```

Caddy handles TLS automatically via Let's Encrypt. `flush_interval -1` disables buffering (required for large layer downloads).

### Traefik (Docker labels)

```yaml
labels:
  - "traefik.enable=true"
  - "traefik.http.routers.drevnix.rule=Host(`drevnix.company.com`)"
  - "traefik.http.routers.drevnix.entrypoints=websecure"
  - "traefik.http.routers.drevnix.tls.certresolver=letsencrypt"
  - "traefik.http.services.drevnix.loadbalancer.server.port=8000"
  - "traefik.http.services.drevnix.loadbalancer.responseForwarding.flushInterval=1ms"
```

### TRUSTED_PROXIES — X-Forwarded-For and real client IPs

TRUSTED_PROXIES controls how Drevnix resolves the real client IP from incoming requests. It affects audit log client_ip values and rate-limiting buckets. Misconfiguring this means audit logs show the proxy's IP instead of real clients, and rate limiting misfires. Set it correctly before going to production.

**Decision guide — which value should I use?**

Step 1: Is Drevnix directly reachable from the internet (no firewall, load balancer, or proxy in front)?
  → Yes: leave TRUSTED_PROXIES unset. Done.
  → No: continue to step 2.

Step 2: Do you need to restrict which specific proxy IPs are trusted?
  → No (most deployments): set TRUSTED_PROXIES=*
    Correct for nginx, Traefik, Caddy, AWS ALB, GCP LB, Hetzner LB, Cloudflare, or any chain of proxies,
    as long as Drevnix is not directly internet-reachable (firewall/security group only allows the proxy).
  → Yes: set TRUSTED_PROXIES to a comma-separated CIDR list of your proxy IPs.

Summary:

| Value          | When to use                                              |
|----------------|----------------------------------------------------------|
| unset          | App exposed directly to the internet, no proxy           |
| *              | App behind any proxy/LB, not directly internet-reachable |
| 10.0.0.0/8,... | Precise CIDR-based proxy trust                           |

**Mode details:**

TRUSTED_PROXIES unset (default):
  X-Forwarded-For is ignored. remote-addr is always used as the client IP.
  Safe for direct deployments — spoofed headers have no effect.

TRUSTED_PROXIES=*:
  X-Forwarded-For is always trusted. The leftmost token is used as the client IP,
  falling back to remote-addr if the header is absent.
  IMPORTANT: Only use * when Drevnix is not directly reachable from the internet.
  If it is, any client can forge their IP via X-Forwarded-For.

TRUSTED_PROXIES=<CIDRs>:
  X-Forwarded-For is trusted only when remote-addr falls within one of the specified CIDRs.
  Otherwise remote-addr is used directly.
  Accepts a comma-separated list of IPv4 or IPv6 CIDR ranges.
  A single host is /32 (IPv4) or /128 (IPv6).
  A malformed CIDR causes a startup error rather than silently failing mid-request.

Examples:

```
# Most deployments: behind a proxy, app not directly internet-reachable
TRUSTED_PROXIES=*

# Precise control: only trust requests arriving from these proxy subnets
TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12
```

**Behavior matrix:**

| Scenario                        | TRUSTED_PROXIES | TCP remote addr     | X-Forwarded-For     | IP used     |
|---------------------------------|-----------------|---------------------|---------------------|-------------|
| Direct deployment               | unset           | 1.2.3.4             | 9.9.9.9 (spoofed)   | 1.2.3.4     |
| Direct deployment               | unset           | 1.2.3.4             | absent              | 1.2.3.4     |
| Behind proxy (wildcard)         | *               | 10.0.0.1 (proxy)    | 1.2.3.4 (client)    | 1.2.3.4     |
| Behind proxy (wildcard), no XFF | *               | 10.0.0.1            | absent              | 10.0.0.1    |
| Behind proxy (CIDR)             | 10.0.0.0/8      | 10.0.0.1 (proxy)    | 1.2.3.4 (client)    | 1.2.3.4     |
| Behind proxy, multi-hop         | 10.0.0.0/8      | 10.0.0.1            | 1.2.3.4, 10.0.0.2   | 1.2.3.4     |
| Behind proxy, no XFF header     | 10.0.0.0/8      | 10.0.0.1            | absent              | 10.0.0.1    |
| Untrusted remote (CIDR mode)    | 10.0.0.0/8      | 5.5.5.5             | 9.9.9.9 (spoofed)   | 5.5.5.5     |

TRUSTED_PROXIES applies to portal login, proxy auth, and REST API auth. One setting covers the entire application.

---

## Initial Admin and License Activation

### Step 0: Have your license key ready

You need a valid license key before Drevnix is fully operational. Get one at https://drevnix.tech/get-license before continuing. The key is entered in the portal immediately after first login.

### Creating the first admin account

Drevnix ships with no accounts. There are two ways to create the initial admin:

**Option A — environment variables (recommended for all automated, scripted, or Swarm setups):**

Set `DREVNIX_INITIAL_ADMIN_USERNAME` and `DREVNIX_INITIAL_ADMIN_PASSWORD` before first startup. Drevnix creates the account automatically and these vars are ignored on all subsequent starts.

For `docker run` or Docker Compose:
```bash
-e DREVNIX_INITIAL_ADMIN_USERNAME=admin \
-e DREVNIX_INITIAL_ADMIN_PASSWORD=a-strong-password
```

For Docker Swarm — export to the shell before `docker stack deploy` (do NOT put in a `.env` file — Swarm does not read it):
```bash
export DREVNIX_INITIAL_ADMIN_USERNAME=admin
export DREVNIX_INITIAL_ADMIN_PASSWORD=a-strong-password
docker stack deploy --with-registry-auth -c stack.yml drevnix
```

**Option B — interactive CLI (only for docker run / Docker Compose installs):**

```bash
docker exec -it drevnix java -jar /opt/drevnix.jar init-admin --config=/etc/drevnix/config.edn
```

Prompts for username and password. Creates a super-admin and exits. Not suitable for Swarm — use Option A instead.

Both options produce the same result. All subsequent user management is through the portal.

### Activating your license (first thing after login)

1. Open the portal (`http://your-host:8001`)
2. Sign in with the admin account
3. Go to **Settings** in the sidebar
4. Paste the license key into the **License Key** field
5. Click **Save**

Takes effect immediately. No restart. The Settings page shows active features, limits, and expiration date.

### License expiry and grace period

When a license expires, Drevnix enters a **2-day grace period** during which it continues operating normally. After the grace period, access to the portal and proxy is blocked until a valid license is applied. Renew before expiry to avoid interruption.

---

## Managing Upstreams

An upstream is a Docker registry that Drevnix proxies to. Credentials are encrypted at rest (AES256-GCM) and never returned by the API after creation.

### Supported registries

Any Docker Registry V2-compatible registry is supported:

| Registry | URL |
|----------|-----|
| GitHub Container Registry | `https://ghcr.io` |
| Docker Hub | `https://registry-1.docker.io` |
| Amazon ECR | `https://<account>.dkr.ecr.<region>.amazonaws.com` |
| Google Artifact Registry | `https://<region>-docker.pkg.dev` |
| Azure Container Registry | `https://<name>.azurecr.io` |
| Private Harbor / Nexus | `https://your-registry.internal` |

### Creating an upstream

**Via portal:** Upstreams -> Add Upstream

**Via API:**

```bash
curl -X POST http://drevnix.company.com:8002/v1/upstreams \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "id": "ghcr",
    "address": "https://ghcr.io",
    "username": "your-github-username",
    "password": "ghp_yourPAThere"
  }'
```

| Field | Description |
|-------|-------------|
| `id` | Short slug used in pull URLs (e.g. `ghcr`, `dockerhub`, `ecr-prod`). Cannot be changed after creation. |
| `address` | Full registry URL including scheme. |
| `username` | Upstream credential username. Omit for public registries. |
| `password` | Upstream credential password. Encrypted at rest, never returned by the API. |

### Rotating upstream credentials

Update credentials without affecting any clients - clients authenticate to Drevnix, not to the upstream:

```bash
curl -X PUT http://drevnix.company.com:8002/v1/upstreams/ghcr \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "username": "your-github-username",
    "password": "ghp_newPAThere"
  }'
```

### Amazon ECR notes

ECR tokens expire every 12 hours. Automate credential rotation:

```bash
#!/bin/bash
# Run every 6 hours via cron or a scheduled Lambda

TOKEN=$(aws ecr get-login-password --region us-east-1)

curl -X PUT http://drevnix.company.com:8002/v1/upstreams/ecr-prod \
  -u admin:${DREVNIX_ADMIN_PASSWORD} \
  -H "Content-Type: application/json" \
  -d "{\"username\": \"AWS\", \"password\": \"${TOKEN}\"}"
```

### Listing upstreams

```bash
curl http://drevnix.company.com:8002/v1/upstreams \
  -u admin:password
```

Passwords are never included in the response.

### Deleting an upstream

```bash
curl -X DELETE http://drevnix.company.com:8002/v1/upstreams/ghcr \
  -u admin:password
```

Clients with permissions on this upstream will receive `404` after deletion. Update or remove related permissions.

---

## Managing Clients

A client is an identity that authenticates to the proxy (`:8000`) using Docker HTTP Basic Auth. Client passwords are bcrypt-hashed on creation and never stored in plaintext. If a password is lost, delete the client and create a new one.

### Creating a client

**Via portal:** Clients -> Add Client

**Via API:**

```bash
curl -X POST http://drevnix.company.com:8002/v1/clients \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "id": "ci-pipeline-prod",
    "password": "a-strong-random-password"
  }'
```

With an expiration date (ISO 8601):

```bash
curl -X POST http://drevnix.company.com:8002/v1/clients \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "id": "contractor-alice",
    "password": "temp-password",
    "expiration_time": "2025-06-01T00:00:00Z"
  }'
```

### Recommended client patterns

| Pattern | Example ID | Notes |
|---------|-----------|-------|
| One per CI pipeline | `ci-pipeline-prod` | Scope permissions to only the images that pipeline needs |
| One per developer | `dev-alice` | Revoke individually if needed |
| One per microservice | `svc-payments` | Pull only its own base image |
| Temporary contractor | `contractor-alice` | Always set an expiration date |

### Expiration dates

Clients with an expiration date automatically return `401` once the date passes. No manual cleanup. Use for:

- Contractors and third-party access
- CI clients for ephemeral environments
- Any time-boxed access

### Listing, updating, and deleting clients

```bash
# List all clients (supports ?limit= and ?offset=)
curl http://drevnix.company.com:8002/v1/clients \
  -u admin:password

# Update expiration date
curl -X PUT http://drevnix.company.com:8002/v1/clients/contractor-alice \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{"expiration_time": "2025-12-31T00:00:00Z"}'

# Delete (access revoked immediately)
curl -X DELETE http://drevnix.company.com:8002/v1/clients/contractor-alice \
  -u admin:password
```

Passwords cannot be updated. Delete and recreate the client to change a password.

---

## Managing Permissions

Permissions define which repositories a client may pull. Default policy is **deny-all**. A client with no permissions cannot pull anything.

### Pattern syntax

Format: `[upstream-id]/[repository-path]` with an optional trailing wildcard.

| Pattern | What it allows |
|---------|---------------|
| `*` | Everything: all upstreams, all repositories |
| `ghcr/*` | All repositories on the `ghcr` upstream |
| `ghcr/myorg/*` | All images under `myorg` on `ghcr` |
| `ghcr/myorg/api` | Exactly `ghcr/myorg/api` - nothing else |
| `dockerhub/library/*` | All official Docker Hub library images |
| `dockerhub/library/nginx` | Only the nginx image from Docker Hub |

**Rules:**
- Wildcards (`*`) can only appear at the **end** of a pattern
- `ghcr/*/api` is not valid - mid-path wildcards are not supported
- A client can have multiple permission entries
- If **any** permission matches the requested repository, access is granted
- No match -> `403 Forbidden`

### Creating a permission

**Via portal:** Permissions -> Add Permission, or from the client's detail page

**Via API:**

```bash
curl -X POST http://drevnix.company.com:8002/v1/permissions \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "ci-pipeline-prod",
    "repository": "ghcr/myorg/*"
  }'
```

### Permission examples by use case

**CI pipeline: only its own image:**
```json
{"client_id": "ci-pipeline-payments", "repository": "ghcr/myorg/payments"}
```

**Developer: all company images plus official Docker Hub images:**
```json
{"client_id": "dev-alice", "repository": "ghcr/myorg/*"}
{"client_id": "dev-alice", "repository": "dockerhub/library/*"}
```

**Contractor: single upstream, single org:**
```json
{"client_id": "contractor-alice", "repository": "ghcr/partner-org/*"}
```

**Emergency break-glass (use sparingly):**
```json
{"client_id": "ops-break-glass", "repository": "*"}
```

### Listing and deleting permissions

```bash
# All permissions
curl http://drevnix.company.com:8002/v1/permissions \
  -u admin:password

# Filtered by client
curl "http://drevnix.company.com:8002/v1/permissions?client_id=ci-pipeline-prod" \
  -u admin:password

# Delete by permission ID (access revoked immediately)
curl -X DELETE http://drevnix.company.com:8002/v1/permissions/42 \
  -u admin:password
```

To change a permission pattern, delete the existing entry and create a new one.

---

## Quick Start: End-to-End Pull

This walks through adding `ghcr.io` as an upstream, creating a client, granting access, and pulling an image. Assumes Drevnix is running and licensed.

### 1. Add the upstream

```bash
curl -X POST http://drevnix.company.com:8002/v1/upstreams \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "id": "ghcr",
    "address": "https://ghcr.io",
    "username": "your-github-username",
    "password": "ghp_yourPATWithReadPackagesScope"
  }'
```

Or via portal: **Upstreams -> Add Upstream** with ID `ghcr`, URL `https://ghcr.io`, and your GitHub PAT (needs `read:packages` scope).

### 2. Create a client

```bash
curl -X POST http://drevnix.company.com:8002/v1/clients \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "id": "ci-pipeline",
    "password": "a-strong-random-password"
  }'
```

Or via portal: **Clients -> Add Client**, click **Generate** for the password (shown only once).

### 3. Grant permission

```bash
curl -X POST http://drevnix.company.com:8002/v1/permissions \
  -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "ci-pipeline",
    "repository": "ghcr/myorg/myapp"
  }'
```

### 4. Docker login and pull

```bash
echo "a-strong-random-password" | docker login drevnix.company.com:8000 \
  --username ci-pipeline \
  --password-stdin

docker pull drevnix.company.com:8000/ghcr/myorg/myapp:latest
```

### 5. Verify in the audit log

```bash
curl "http://drevnix.company.com:8002/v1/audit?client_id=ci-pipeline&limit=5" \
  -u admin:password
```

Or check the portal: **Audit Logs**. You should see an entry with the client ID, upstream, repository, tag, HTTP status, and timestamp.

---

## CI/CD Integration

### GitHub Actions

```yaml
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Log in to Drevnix
        uses: docker/login-action@v3
        with:
          registry: drevnix.company.com:8000
          username: ${{ secrets.DREVNIX_CLIENT_ID }}
          password: ${{ secrets.DREVNIX_CLIENT_SECRET }}

      - name: Pull base image through Drevnix
        run: docker pull drevnix.company.com:8000/ghcr/myorg/myapp:latest
```

Store `DREVNIX_CLIENT_ID` and `DREVNIX_CLIENT_SECRET` as repository or organisation secrets. The upstream registry credentials (GitHub PAT) never need to leave Drevnix.

### GitLab CI

```yaml
before_script:
  - echo "$DREVNIX_CLIENT_SECRET" | docker login $DREVNIX_HOST:8000
      --username "$DREVNIX_CLIENT_ID" --password-stdin

pull-image:
  script:
    - docker pull $DREVNIX_HOST:8000/ghcr/myorg/myapp:latest
```

### Kubernetes / containerd (daemon config)

Add the Drevnix proxy as a mirror in your container runtime config:

```json
{
  "registry-mirrors": [],
  "insecure-registries": [],
  "auths": {
    "drevnix.company.com:8000": {
      "auth": "base64(ci-pipeline:password)"
    }
  }
}
```

Or use a Kubernetes pull secret:

```bash
kubectl create secret docker-registry drevnix-pull-secret \
  --docker-server=drevnix.company.com:8000 \
  --docker-username=ci-pipeline \
  --docker-password=a-strong-random-password \
  --namespace=my-namespace
```

---

## Security Hardening

### Network isolation

Only the proxy port needs to be public-facing:

| Port | Exposure |
|------|---------|
| `:8000` (proxy) | Public - Docker clients reach this |
| `:8001` (portal) | Internal / VPN only |
| `:8002` (REST API) | Internal / VPN only |

AWS security group example:
```
Inbound:
  8000 from developer/CI IP ranges
  8001 from VPN CIDR only
  8002 from VPN CIDR only

Outbound:
  443 to upstream registries (ghcr.io, docker.io, etc.)
```

### ENCRYPTION_KEY

- Generate with `openssl rand -hex 32`
- Store in a secrets manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager) - not in `.env` files or source control
- Back it up. Losing it makes all stored upstream credentials unreadable
- To rotate, use: `docker exec -it drevnix java -jar /opt/drevnix.jar change-encryption-key --config=/etc/drevnix/config.edn`

### TLS everywhere

Never expose Drevnix over plain HTTP on a public network. Put nginx, Caddy, or Traefik in front. See [TLS / HTTPS](#tls--https).

### Least-privilege client permissions

Grant each client only the images it actually needs:

```
# Too broad - avoid unless necessary
ghcr/*

# Scoped to org - acceptable for developer clients
ghcr/myorg/*

# Minimal - preferred for production CI pipelines
ghcr/myorg/payments
```

Review client permissions quarterly. Delete unused clients immediately.

### Client expiration dates

Set expiration dates on all contractor, temporary, and third-party clients. Expired clients automatically return `401`. No manual revocation needed.

### Rate limiting

Drevnix applies in-memory rate limiting to login endpoints. After **5 failed attempts in a 15-minute window**, the username/IP combination is locked out for 15 minutes. Successful authentication resets the counter. No configuration required.

### PostgreSQL connection security

Always use SSL for remote databases:

```bash
JDBC_URL=jdbc:postgresql://host:5432/drevnix?ssl=true&sslmode=require
```

### Audit log review

Periodically check the audit log for:
- Unexpected `403` responses (misconfigured client or probing)
- Access to sensitive upstreams (`ecr-prod`) from unexpected clients
- Unexpected client IDs (may indicate leaked credentials)

Set `AUDIT_RETENTION_DAYS` to at least `90`, or `365`+ for compliance frameworks.

---

## Health Checks and Verification

### Health endpoint

```bash
curl http://localhost:8002/health
# -> 200 OK
```

Wire into your load balancer health check, Docker `HEALTHCHECK`, or Kubernetes liveness probe:

```yaml
# Docker Compose
healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost:8002/health"]
  interval: 30s
  timeout: 5s
  retries: 3
  start_period: 10s

# Kubernetes
livenessProbe:
  httpGet:
    path: /health
    port: 8002
  initialDelaySeconds: 10
  periodSeconds: 30
```

### Verifying a pull works end-to-end

```bash
# 1. Login
echo "client-password" | docker login drevnix.company.com:8000 \
  --username my-client --password-stdin

# 2. Pull
docker pull drevnix.company.com:8000/ghcr/myorg/myapp:latest

# 3. Check audit log for the event
curl "http://drevnix.company.com:8002/v1/audit?limit=1" \
  -u admin:password

# Expected: entry with "status": 200 and "client": "my-client"
```

### Common error codes

| Code | Meaning | Fix |
|------|---------|-----|
| `401` | Client credentials wrong or client expired | Check client ID/password; check expiration date |
| `403` | Client authenticated but no matching permission | Add a permission for the requested repository |
| `404` | Upstream not found or image not found upstream | Check upstream ID in the pull URL; verify image exists upstream |
| `502` / `503` | Drevnix cannot reach the upstream registry | Check network/firewall; verify upstream URL and credentials |

---

*For the full documentation index, visit https://drevnix.tech/docs*  
*License inquiries: info@drevnix.tech*
