Skip to content

Static Registry Output Plan

Status: Proposed. Written 2026-06-20 and left in the repository root until 2026-12-01, when it was moved here and registered. Nothing in it has been implemented. This document predates PLAN-TEMPLATE.md, so it does not carry the Prompt, Situation and Mission sections a new plan would.

This document outlines the design for a new occystrap output that generates a static file structure suitable for serving as a read-only Docker registry via nginx with the njs (JavaScript) module for dynamic manifest headers.

Motivation

Traditional Docker registries (Docker Registry, Harbor, etc.) require:

  • A running daemon process
  • Database or filesystem state management
  • Authentication/authorization logic
  • Blob upload handling

For read-only use cases (distributing pre-built images, airgapped deployments, CDN-backed distribution), this complexity is unnecessary. A static file structure served by nginx offers:

  • Extreme scalability: nginx can serve millions of requests; CDNs can cache globally
  • Simplicity: Minimal daemon, no database, no complex state
  • Cost efficiency: Static hosting is cheap; blobs can be served from S3/CDN
  • Reliability: Blobs are just files; the njs handler is trivial
  • Offline capability: Copy the directory to a USB drive for airgapped use

Prior Art and Why It Falls Short

Several toy implementations exist using S3 buckets or static hosting, but they typically fail because:

  1. Missing Docker-Content-Digest header: Docker clients require this header on manifest responses, containing the SHA256 of the response body. Without it, pulls fail with cryptic errors.

  2. Wrong Content-Type: Docker requires specific MIME types like application/vnd.docker.distribution.manifest.v2+json, not generic application/json.

  3. No multi-architecture support: Manifest lists/indices require proper handling to serve the correct platform-specific manifest.

  4. No tag resolution: Tags need to resolve to digest-addressed files.

Docker Registry HTTP API V2 - Read-Only Subset

For a pull-only registry, we need these endpoints:

Endpoint Method Purpose
/v2/ GET Version check (must return 200 with {})
/v2/<name>/manifests/<reference> GET Manifest by tag or digest
/v2/<name>/blobs/<digest> GET Layer or config blob
/v2/<name>/tags/list GET List available tags (optional)
/v2/_catalog GET List all repositories (optional)

Critical Response Requirements

Manifests require these headers:

Content-Type: application/vnd.docker.distribution.manifest.v2+json
Docker-Content-Digest: sha256:<hex-digest-of-response-body>

The Docker-Content-Digest header MUST match the SHA256 hash of the exact bytes returned in the response body. This is non-negotiable - Docker clients verify this.

Content-Type variations that must be served correctly:

Resource Content-Type
Manifest v2 application/vnd.docker.distribution.manifest.v2+json
OCI Manifest application/vnd.oci.image.manifest.v1+json
Manifest List application/vnd.docker.distribution.manifest.list.v2+json
OCI Index application/vnd.oci.image.index.v1+json
Config blob application/vnd.docker.container.image.v1+json
Layer blob application/octet-stream

Architecture: nginx + njs Module

The challenge with a purely static approach is that nginx cannot compute the Docker-Content-Digest header dynamically. Options considered:

Approach Pros Cons
Pure static nginx No dependencies Config grows per-image; reload needed
OpenResty (nginx+Lua) Dynamic headers Requires OpenResty, not stock nginx
nginx njs module Dynamic headers, in-process Requires njs module
Python FastCGI No nginx modules External daemon (fcgiwrap), IPC overhead
Apache mod_lua Dynamic headers Less common, similar complexity

Chosen Approach: nginx + njs

The njs module (nginx's built-in JavaScript scripting engine) handles manifest requests in-process, while nginx serves blobs as static files:

  • nginx serves blobs (layers and config): These are static files representing 99%+ of bandwidth. nginx excels at this.
  • njs handles manifests: A small JavaScript function reads the manifest file, computes the SHA256 digest, sets the required headers, and returns the response -- all within the nginx worker process.

This provides:

  1. Scalability: Blobs (the heavy traffic) served at full nginx speed
  2. No external processes: njs runs inside nginx workers -- no IPC, no sockets, no separate daemon to manage
  3. No config regeneration: Adding images doesn't require nginx reload
  4. Minimal dependencies: Single package (libnginx-mod-http-js on Debian/Ubuntu) with no Python runtime required on the server
  5. Portability: The registry directory is fully self-contained (just files
  6. an nginx config snippet + a .js file)

Why njs Over Python FastCGI

An earlier version of this plan proposed a Python CGI script running under fcgiwrap. The njs approach is preferred because:

Aspect njs Python FastCGI
Runtime deps on server libnginx-mod-http-js Python3 + fcgiwrap
External processes None (in-process) fcgiwrap daemon + socket
IPC overhead Zero Unix socket per request
Deployment nginx config + .js file nginx config + .cgi + fcgiwrap service
Airgapped portability No Python needed on target Python required on target

The manifest-serving logic is trivial (read file, SHA256, set header), well within njs's capabilities. There is no need for Python's full standard library.

Traffic Flow

                                    ┌─────────────────────┐
                                    │                     │
     GET /v2/library/nginx/blobs/   │      nginx          │
    ─────────────────────────────────►  (static files)    │
                                    │                     │
                                    │  /_blobs/sha256:... │
                                    └─────────────────────┘

                                    ┌─────────────────────┐
     GET /v2/library/nginx/         │                     │
         manifests/latest           │  nginx + njs        │
    ─────────────────────────────────►  (in-process JS)   │
                                    │                     │
                                    │  Reads file,        │
                                    │  computes digest,   │
                                    │  sets headers       │
                                    └─────────────────────┘

Proposed Directory Structure

registry-root/
├── v2/
│   ├── _catalog.json                       # {"repositories":["library/nginx",...]}
│   └── <namespace>/
│       └── <image>/
│           ├── manifests/
│           │   ├── latest                  # Tag file (copy of manifest)
│           │   ├── latest.meta             # Metadata: content_type
│           │   ├── v1.0                    # Tag file (copy of manifest)
│           │   ├── v1.0.meta               # Metadata: content_type
│           │   ├── sha256:abc123...        # Manifest by digest
│           │   └── sha256:abc123....meta   # Metadata: content_type
│           ├── blobs/
│           │   └── sha256:...              # Symlinks to shared blobs
│           └── tags/
│               └── list                    # {"name":"...","tags":["latest",...]}
├── _blobs/
│   └── sha256:...                          # Content-addressed blob storage
├── registry.js                             # njs script for manifest serving
└── nginx.conf.snippet                      # Generated nginx configuration

Key Design Decisions

  1. Content-addressed blob storage: All blobs live in _blobs/ with symlinks from image-specific paths. This provides automatic deduplication when the same layer appears in multiple images.

  2. Tag files are copies, not symlinks: The njs handler reads the file and computes its digest. Copies ensure consistent behaviour.

  3. Metadata sidecar files: Each manifest has a .meta file containing:

    {
      "content_type": "application/vnd.docker.distribution.manifest.v2+json"
    }
    
    The digest is computed dynamically by the njs handler, ensuring it always matches the actual file content.

  4. Self-contained deployment: The njs script is generated into the registry directory, making the entire registry self-contained and portable.

njs Manifest Handler

The njs script is a lightweight JavaScript module that nginx loads via js_import. It runs inside the nginx worker process with no IPC overhead.

The script:

  1. Handles /v2/ version endpoint
  2. Handles /v2/<name>/manifests/<reference> requests
  3. Handles /v2/<name>/tags/list requests
  4. Handles /v2/_catalog requests
  5. Reads manifest files from disk
  6. Reads content-type from .meta sidecar files
  7. Computes SHA256 digest of the manifest content
  8. Returns response with correct headers

njs Script Implementation

// Static Registry Manifest Handler (njs)
//
// Serves Docker/OCI manifests with correct Docker-Content-Digest headers.
// Generated by occystrap - https://github.com/shakenfist/occystrap
//
// This script is loaded by nginx via js_import and called from
// js_content directives in the nginx configuration.

var fs = require('fs');
var crypto = require('crypto');

// Registry root - set via nginx variable $registry_root
function registryRoot(r) {
    return r.variables.registry_root;
}

function sendError(r, code, message) {
    r.headersOut['Content-Type'] = 'application/json';
    r.return(code, JSON.stringify({
        errors: [{code: 'NOT_FOUND', message: message}]
    }));
}

function serveManifest(r) {
    var match = r.uri.match(/^\/v2\/(.+)\/manifests\/(.+)$/);
    if (!match) {
        sendError(r, 404, 'Not Found');
        return;
    }

    var name = match[1];
    var reference = match[2];
    var root = registryRoot(r);
    var manifestPath = root + '/v2/' + name + '/manifests/' + reference;
    var metaPath = manifestPath + '.meta';

    var content;
    try {
        content = fs.readFileSync(manifestPath);
    } catch (e) {
        sendError(r, 404, 'Not Found');
        return;
    }

    // Read content-type from sidecar, or use default
    var contentType =
        'application/vnd.docker.distribution.manifest.v2+json';
    try {
        var meta = JSON.parse(fs.readFileSync(metaPath));
        contentType = meta.content_type || contentType;
    } catch (e) {
        // Use default content-type if .meta file is missing/invalid
    }

    // Compute digest
    var hash = crypto.createHash('sha256');
    hash.update(content);
    var digest = 'sha256:' + hash.digest('hex');

    // Cache headers: digest references are immutable, tags are not
    if (reference.startsWith('sha256:')) {
        r.headersOut['Cache-Control'] =
            'public, max-age=31536000, immutable';
    } else {
        r.headersOut['Cache-Control'] = 'public, max-age=300';
    }

    r.headersOut['Content-Type'] = contentType;
    r.headersOut['Docker-Content-Digest'] = digest;
    r.return(200, content);
}

function serveVersionCheck(r) {
    r.headersOut['Content-Type'] = 'application/json';
    r.return(200, '{}');
}

function serveCatalog(r) {
    var root = registryRoot(r);
    var catalogPath = root + '/v2/_catalog.json';

    try {
        var content = fs.readFileSync(catalogPath);
        r.headersOut['Content-Type'] = 'application/json';
        r.return(200, content);
    } catch (e) {
        r.headersOut['Content-Type'] = 'application/json';
        r.return(200, '{"repositories":[]}');
    }
}

function serveTagsList(r) {
    var match = r.uri.match(/^\/v2\/(.+)\/tags\/list$/);
    if (!match) {
        sendError(r, 404, 'Not Found');
        return;
    }

    var name = match[1];
    var root = registryRoot(r);
    var tagsPath = root + '/v2/' + name + '/tags/list';

    try {
        var content = fs.readFileSync(tagsPath);
        r.headersOut['Content-Type'] = 'application/json';
        r.return(200, content);
    } catch (e) {
        sendError(r, 404, 'Not Found');
    }
}

export default {
    serveManifest: serveManifest,
    serveVersionCheck: serveVersionCheck,
    serveCatalog: serveCatalog,
    serveTagsList: serveTagsList
};

njs Module Setup

The njs module is available as a standard package on modern Linux distributions:

# Debian/Ubuntu (Bookworm+, 22.04+)
sudo apt install libnginx-mod-http-js

# RHEL/CentOS/Fedora (from nginx.org repos)
sudo dnf install nginx-mod-http-js

# Alpine
apk add nginx-mod-http-js

The module is loaded automatically via a config fragment in /etc/nginx/modules-enabled/ on Debian/Ubuntu. On other distributions, add load_module modules/ngx_http_js_module.so; to nginx.conf.

No external daemons, sockets, or process managers are required.

nginx Configuration

The generated nginx config uses js_import to load the njs script, serves blobs as static files, and routes manifest/metadata requests to njs handlers:

# Static Docker Registry - generated by occystrap
# Include this in your server block
#
# Requirements:
#   - njs module installed
#   - Debian/Ubuntu: apt install libnginx-mod-http-js

# Import the njs manifest handler
js_import registry from /var/www/registry/registry.js;

# Registry root path (used by njs to locate files)
set $registry_root /var/www/registry;

# API version endpoint
location = /v2/ {
    js_content registry.serveVersionCheck;
}

# Catalog endpoint
location = /v2/_catalog {
    js_content registry.serveCatalog;
}

# Tags list endpoints
location ~ ^/v2/(.+)/tags/list$ {
    js_content registry.serveTagsList;
}

# Manifest endpoints (njs computes Docker-Content-Digest dynamically)
location ~ ^/v2/(.+)/manifests/(.+)$ {
    js_content registry.serveManifest;
}

# Blob endpoints - served directly by nginx (static files)
location ~ ^/v2/(.+)/blobs/(sha256:.+)$ {
    alias /var/www/registry/_blobs/$2;
    default_type application/octet-stream;
    add_header Cache-Control "public, max-age=31536000, immutable";

    # Enable sendfile for efficient large file transfer
    sendfile on;
    tcp_nopush on;
}

Cache Headers

  • Blobs: Cache-Control: public, max-age=31536000, immutable - content- addressed, never change
  • Digest-addressed manifests: Same as blobs - immutable
  • Tag-addressed manifests: Cache-Control: public, max-age=300 - tags can be updated

Implementation Plan

Phase 1: Core Static Registry Writer

New file: occystrap/outputs/static_registry.py

class StaticRegistryWriter(ImageOutput):
    """Write images to a static file structure for serving via nginx."""

    def __init__(self, registry_root, image_name, tag):
        self.registry_root = registry_root
        self.image_name = image_name  # e.g., "library/nginx"
        self.tag = tag

        self._blobs_dir = os.path.join(registry_root, '_blobs')
        self._image_dir = os.path.join(registry_root, 'v2', image_name)
        self._config_digest = None
        self._layers = []

Key methods:

  • fetch_callback(digest): Check if blob already exists in _blobs/, skip if present (deduplication)
  • process_image_element(element_type, name, data): Write blobs to _blobs/, create symlinks in image directory
  • finalize(): Write manifest files, tags list, update catalog, generate server files

Phase 2: njs Script and Config Generation

New file: occystrap/outputs/static_registry_server.py

Functions to generate:

  • registry.js - The njs script for manifest serving
  • nginx.conf.snippet - nginx configuration with js_import and js_content directives

These are generated/updated when finalize() is called, ensuring the registry directory is always self-contained.

Phase 3: URI Integration

Update: occystrap/uri.py

Add new URI scheme:

static-registry:///path/to/registry

Update: occystrap/pipeline.py

Register the new output in PipelineBuilder.

Phase 4: CLI Commands

New command: occystrap static-registry-init

# Initialize a new static registry (creates directory structure + njs script)
occystrap static-registry-init /path/to/registry

New command: occystrap static-registry-regenerate

# Regenerate njs script and nginx config (e.g., after manual changes)
occystrap static-registry-regenerate /path/to/registry

Phase 5: Multi-Architecture Support

Handle manifest lists/indices:

  • Store both the manifest list and all platform-specific manifests
  • Each gets its own .meta file with correct content-type
  • The njs handler serves both transparently

Usage Examples

Basic Usage

# Add an image to a static registry
occystrap process registry://docker.io/library/nginx:latest \
    static-registry:///var/www/registry

# Add another image (blobs are deduplicated automatically)
occystrap process registry://docker.io/library/redis:7 \
    static-registry:///var/www/registry

Production Deployment

# Install the njs module (if not already installed)
sudo apt install libnginx-mod-http-js

# Configure nginx - link the generated snippet
sudo ln -s /var/www/registry/nginx.conf.snippet \
    /etc/nginx/snippets/static-registry.conf

# Create site config
cat <<'EOF' | sudo tee /etc/nginx/sites-available/registry
server {
    listen 443 ssl http2;
    server_name registry.example.com;

    ssl_certificate /etc/letsencrypt/live/registry.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/registry.example.com/privkey.pem;

    include snippets/static-registry.conf;
}
EOF

sudo ln -s /etc/nginx/sites-available/registry /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Pulling from the Static Registry

docker pull registry.example.com/library/nginx:latest

Adding Images Without Restart

# Add a new image - no nginx reload needed!
occystrap process registry://docker.io/library/python:3.11 \
    static-registry:///var/www/registry

# The njs handler reads files from disk on each request
docker pull registry.example.com/library/python:3.11

Testing Strategy

Unit Tests

  • Directory structure generation
  • Manifest writing with correct format
  • Blob deduplication logic
  • .meta file generation
  • Tags list and catalog generation
  • njs script generation (verify generated JS is syntactically valid)

Functional Tests

  1. Basic pull test: Generate static registry, configure nginx + njs, pull image with Docker
  2. Multi-image test: Add multiple images, verify deduplication
  3. Multi-arch test: Add multi-architecture image, pull on different platforms
  4. Dynamic update test: Add new image, pull immediately (no restart needed)

CI Requirements

  • Docker client for pull verification
  • nginx with njs module for full integration tests
  • No Python required on the serving side (only for occystrap itself)

Alternative: Pure Static Mode (Small Registries)

For registries with fewer than ~100 images where nginx config size isn't a concern, we can offer a pure static mode that generates per-manifest nginx location blocks:

occystrap process registry://docker.io/library/nginx:latest \
    "static-registry:///var/www/registry?mode=pure-static"

This generates nginx config with embedded digest headers, requiring no njs module but needing nginx reload when images are added.

Alternative: Python FastCGI Fallback

For environments where installing the njs module is not possible (e.g., locked-down package policies, very old distributions), a Python CGI fallback can be used instead. This requires fcgiwrap and Python 3 on the server:

occystrap process registry://docker.io/library/nginx:latest \
    "static-registry:///var/www/registry?server=fastcgi"

This generates a registry.cgi Python script and an nginx config using fastcgi_pass instead of js_content. The trade-off is an additional external daemon (fcgiwrap) and a Python runtime dependency on the server.

Future Enhancements

S3 Backend

Direct upload to S3 with CloudFront:

occystrap process registry://docker.io/library/nginx:latest \
    static-registry-s3://my-bucket/registry

Would require:

  • S3-compatible output writer for blobs
  • Lambda@Edge or CloudFront Functions for manifest header injection

Authentication

While the registry is read-only, access can be restricted:

  • nginx auth_basic for simple password protection
  • nginx auth_request for integration with external auth
  • Document integration patterns

Garbage Collection

Tool to remove unreferenced blobs:

occystrap static-registry-gc /path/to/registry --dry-run

Mirror Mode

Automatically mirror upstream registries:

occystrap static-registry-mirror \
    --upstream registry-1.docker.io \
    --images library/nginx:latest,library/redis:7 \
    --output /var/www/registry

Estimated Complexity

Phase 1-2: Medium - Core writing logic and njs script generation.

Phase 3-4: Low - URI integration and CLI commands.

Phase 5: Medium - Multi-arch handling.

Total: Moderately complex, building on existing occystrap patterns. The njs script is simple (~80 lines of JS); most complexity is in correct manifest and metadata handling.

Open Questions

  1. Blob symlinks vs hardlinks: Symlinks are more portable but some filesystems don't support them (FAT32, some network mounts). Hardlinks work on more filesystems but can't cross mount points. Recommendation: symlinks by default, with --hardlinks option.

  2. Concurrent writes: What happens if two occystrap process commands run simultaneously? Recommendation: Use atomic writes (write to temp, rename) and document that concurrent writes to the same image/tag are undefined.

  3. Compression: Should the njs handler support gzip/deflate for manifest responses? Manifests are small (<100KB typically), and nginx can handle compression natively. Recommendation: Let nginx handle compression if desired via gzip on; in the location blocks.

  4. Error logging: The njs script can log via r.error() and r.warn(), which write to the nginx error log. Recommendation: Use r.error() for unexpected failures (missing files, parse errors) so they appear in the standard nginx error log alongside other nginx diagnostics.

  5. njs fs.readFileSync blocking: The njs readFileSync call blocks the nginx worker for the duration of the read. Manifests are small (<100KB), so this is negligible in practice. For extremely high-throughput deployments, nginx's worker_processes auto; ensures multiple workers handle concurrent requests. This is a non-issue for any realistic registry workload.

📝 Report an issue with this page