Self-Host SearXNG on VPS: Docker, HTTPS & Production Tuning

Complete guide to deploying SearXNG metasearch on a VPS with Docker Compose, Nginx TLS termination, rate limiting, access control, settings.yml hardening, monitoring

Table of contents
  1. 1.Introduction & Industry Context
  2. 2.Cross-Cutting Parameter & Key Point Overview
  3. 3.Deep-Dive Breakdown & Operational Details
  4. 3.1.Core Image Selection & Version Pinning Strategy
  5. 3.2.Docker Compose Minimum Viable Orchestration & Environment Variable Decoupling
  6. 3.3.settings.yml Fine-Tuning: From “Runs” to “Runs Well”
  7. 3.4.Reverse Proxy & HTTPS Termination: Nginx Production-Grade Config
  8. 3.5.Advanced Access Control: From Basic Auth to Zero-Trust Gateway
  9. 3.6.Upstream Engine Rate Limiting & Health Governance
  10. 3.7.Observability Stack: Logs, Metrics, Tracing
  11. 3.8.Backup, Disaster Recovery & Migration Drills
  12. 3.9.Systemd Service Management (Host-Level)
  13. 4.Sources & References
Self-Host SearXNG on VPS: Docker, HTTPS & Production Tuning

Self-Host SearXNG Search Engine: Full Docker Deployment, HTTPS Hardening & Production Tuning

Introduction & Industry Context

As mainstream search engines deepen user profiling and behavioral tracking, data sovereignty and privacy protection have become core demands for technical communities and individual developers. SearXNG, an active fork of searx, has rapidly become the preferred solution for self-hosted privacy search thanks to its “metasearch” architecture: it builds no index of its own but aggregates results in real time from dozens of upstream engines — Google, Bing, DuckDuckGo, Brave, and others — while stripping all tracking parameters. Compared with centralized SaaS, self-hosting SearXNG places full data control in the user’s hands: query logs stay local, zero ad injection, customizable engine weights and UI themes, and minute-level delivery via Docker.

However, production-grade deployment is far more than a simple docker run. Upstream engines universally enforce strict rate limits and IP reputation checks; a bare instance easily triggers 429/503 responses causing service degradation. Public exposure without HTTPS and access control invites abuse, scraper harvesting, and even permanent bans from upstream providers. Contabo’s official blog post “How to Self-Host SearXNG with Docker on a VPS” (published 10 November 2026) systematically covers image selection, Compose orchestration, reverse proxy TLS termination, basic auth integration, and fine-grained settings.yml tuning — providing a standardized reference paradigm for small-to-medium self-hosted scenarios.

This article uses that tutorial as its skeleton, augmented with Linux container operations battle scars: systemd management, log rotation, Prometheus metrics exposure, multi-instance load balancing, and backup/restore drills — forming a ready-to-deploy “zero-to-one” deep guide. Suitable for site admins, privacy enthusiasts, SME DevOps, and technical decision makers who want a controllable search entry point at controlled cost.

Cross-Cutting Parameter & Key Point Overview

Dimension Key Points Typical Config/Values Applicability & Risk Notes
Base Image searxng/searxng:latest (Docker Hub / GHCR) AMD64/ARM64 multi-arch, ~200 MB image Production must pin a specific tag (e.g. 2026.11.0) to avoid rolling latest upgrades breaking compatibility
Orchestration Docker Compose v2 (docker compose) Single docker-compose.yml + .env file Single-node only; multi-node HA requires Swarm/K8s with shared Redis/settings volumes
Reverse Proxy Nginx / Caddy / Traefik TLS termination Let’s Encrypt auto-issue, enforce HTTPS, HSTS, CSP Must implement rate limiting at proxy layer (e.g. limit_req_zone) or upstream engines will ban VPS IP
Access Control Basic Auth / Authelia / OAuth2-Proxy htpasswd generated auth file mounted to proxy Public instances mandatory; pure LAN/VPN may exempt but audit logging still recommended
Persistent Volumes /etc/searxng (config) + /var/lib/searxng (instance data) Bind mount or Named Volume Settings volume must be in scheduled backup (includes settings.yml, secret_key, custom templates)
Upstream Engine Policy settings.yml engines list enable/disable, weight, request interval Default 20+ engines enabled; trim to 8-12 core sources Too many engines increase latency & ban surface; regularly audit healthcheck endpoint to drop failing sources
Resource Baseline 1 vCore / 1 GB RAM / 5 GB disk minimum Recommended 2 vCore / 2 GB / 10 GB SSD for 20+ QPS concurrent < 512 MB RAM causes Python OOM Kill; high concurrency needs horizontal scale + Redis cache
Monitoring & Logs /healthz readiness probe + stdout JSON logs + /metrics (Prometheus) docker compose logs -f --tail=100 / Loki / Grafana No systemd inside container; log rotation via log-opt max-size=10m max-file=5 or host logrotate

Deep-Dive Breakdown & Operational Details

Core Image Selection & Version Pinning Strategy

Contabo’s tutorial references searxng/searxng:latest, but in production delivery version pinning is a non-negotiable baseline. SearXNG uses a rolling release model; the latest tag always points to the newest build. If an upstream engine API changes (e.g. Google HTML structure shift, Bing parameter signature upgrade), the new image may introduce breaking changes that instantly break your instance. Visit GitHub Releases or Docker Hub Tags, pick an explicit semantic version (e.g. 2026.11.0 or 2026.11.0-debian), and declare it in docker-compose.yml:

services:
 searxng:
 image: searxng/searxng:2026.11.0
 # image: ghcr.io/searxng/searxng:2026.11.0 # alternate GHCR source

The image is based on Debian slim, bundles Python 3.11+, uWSGI, and a default settings.yml. On first start, the entrypoint script checks for /etc/searxng/settings.yml: if missing, it generates from template and writes a random secret_key (used for Flask session signing & CSRF protection); if present, it reuses the existing file. Critical step: immediately after the first docker compose up -d, run docker compose cp searxng:/etc/searxng/settings.yml ./settings.yml.backup to preserve the generated config. All subsequent tuning is done on the host and mounted back into the container, achieving “config-as-code” versioned management.

Docker Compose Minimum Viable Orchestration & Environment Variable Decoupling

The tutorial’s docker-compose.yml skeleton is minimal; production deployment must fill these gaps:

version: '3.8'
services:
 searxng:
 image: searxng/searxng:2026.11.0
 container_name: searxng
 restart: unless-stopped
 networks:
 - searxng_net
 volumes:
 - ./settings.yml:/etc/searxng/settings.yml:ro
 - searxng_data:/var/lib/searxng
 environment:
 - SEARXNG_BASE_URL=https://search.example.com/ # must end with /
 - UWSGI_PROCESSES=4
 - UWSGI_THREADS=2
 healthcheck:
 test: ["CMD", "curl", "-f", "http://localhost:8080/healthz"]
 interval: 30s
 timeout: 10s
 retries: 3
 start_period: 20s
 logging:
 driver: "json-file"
 options:
 max-size: "10m"
 max-file: "5"
 deploy:
 resources:
 limits:
 cpus: '1.5'
 memory: 1.5G
 reservations:
 cpus: '0.5'
 memory: 512M

 # Optional: Redis cache layer (recommended for high concurrency)
 # redis:
 # image: redis:7-alpine
 # command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru
 # volumes:
 # - redis_data:/data
 # networks:
 # - searxng_net

networks:
 searxng_net:
 driver: bridge
 ipam:
 config:
 - subnet: 172.28.0.0/24

volumes:
 searxng_data:
 # redis_data:

Environment Variable Breakdown:

  • SEARXNG_BASE_URL: Base for absolute links (RSS, OpenSearch XML, canonical URLs). Must match the reverse proxy public domain and end with a slash, otherwise frontend assets trigger mixed-content errors.
  • UWSGI_PROCESSES / UWSGI_THREADS: Control uWSGI worker processes and threads. Rule of thumb: processes = CPU cores, threads = 2. Single-instance concurrent capacity ≈ processes × threads × 10 QPS. If Redis is added, processes can be reduced to save memory.
  • healthcheck: Calls built-in /healthz probe (returns 200 OK + JSON {"status": "ok"}), paired with restart: unless-stopped for self-healing.
  • logging + deploy.resources: Cap container log size to prevent filling host disk; CPU/memory quotas prevent “noisy neighbor” queries (e.g. heavy regex filters) from dragging down the whole host.

Network Isolation: Custom searxng_net with explicit subnet avoids IP conflicts with other Compose projects on the host, and simplifies later attachment of Prometheus exporters or sidecar log collectors in the same network.

settings.yml Fine-Tuning: From “Runs” to “Runs Well”

settings.yml is SearXNG’s brain; the tutorial only says “modify as needed”. In practice, the following sections must be reviewed line by line:

1. general Basic Section

general:
 debug: false # Production: never enable — leaks stack traces & env vars
 instance_name: "My Private Search" # Shown in page title & OpenSearch description
 contact_url: "mailto:[email protected]" # Footer contact, lets upstream complaints reach you
 enable_metrics: true # Expose /metrics for Prometheus scraping
 metrics_password: "changeme" # Set strong password, or combine with proxy IP allowlist
 language: "zh-CN" # Default UI language, supports auto-detect via Accept-Language
 safe_search: 1 # 0=off 1=moderate 2=strict; moderate balances false blocks
 autocomplete: "google" # Suggestion source; options: duckduckgo/brave/none
 theme: "simple" # Built-in simple/oscar/dark; production: lock to simple to reduce frontend payload

2. engines Engine Policy — Core Survival Line

Default enables 30+ engines; real-world testing shows a single query fans out to 15+ upstream endpoints concurrently, almost guaranteed to hit per-IP rate limits. Trimming principles:

  • Keep core general: google, bing, brave, duckduckgo, startpage, qwant, mojeek, yandex (if serving Russian users).
  • Vertical on demand: Technical docs keep github, gitlab, stackoverflow; academic keep semantic_scholar, arxiv; code search keep sourcegraph.
  • Disable high-risk: yahoo, baidu, sogou (frequent 403/captcha); wikipedia, wikidata (non-search) convert to shortcut quick-links.
  • Request interval & timeout: Explicitly set request_timeout: 5.0, rate_limit: 1.0 (seconds per request) per engine; in engine_overrides add headers: { User-Agent: "Mozilla/5.0 ... Chrome/120" } for ban-prone sources to mimic browser fingerprint.

3. server & redis Sections

server:
 base_url: "https://search.example.com/" # Must match SEARXNG_BASE_URL exactly
 secret_key: "super-long-random-string-from-first-boot" # Never commit to Git; backup encrypted
 limiter: true # Enable Flask-Limiter basic rate control
 limit: "50/minute" # Global coarse limit; fine-grained at Nginx
 image_proxy: true # Thumbnail proxy, prevents upstream image Referer leak
 method: "POST" # Force POST queries, avoids URL history leakage

redis:
 enabled: false # Single instance: off; cluster mode: true + host/port/db/password

4. branding & ui Polish

  • issue_url, docs_url, public_instances point to your own docs site & instance list page, building brand trust.
  • static_use_cdn: false disables external CDNs (Bootstrap, FontAwesome, etc.); all static assets served via local Nginx cache, eliminating third-party requests entirely.

Config Activation Flow: Edit settings.yml on host → docker compose cp settings.yml searxng:/etc/searxng/settings.yml → docker compose restart searxng (or docker compose kill -s HUP searxng for uWSGI graceful reload). Recommend committing settings.yml to Git (secret_key encrypted via .sops.yaml or git-crypt) for true Infrastructure-as-Code.

Reverse Proxy & HTTPS Termination: Nginx Production-Grade Config

The tutorial advises “put HTTPS and access control in front” but provides no complete Nginx config. Below is a production-ready nginx.conf snippet (assumes Certbot certificates already obtained):

# Rate limit zones: global 30 req/s burst 50, per-IP 10 req/s
limit_req_zone $binary_remote_addr zone=searxng_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=searxng_burst:10m rate=30r/s;

# Upstream definition (single instance; multi-instance: multiple server lines + least_conn)
upstream searxng_backend {
 server 127.0.0.1:8080;
 keepalive 32;
}

server {
 listen 80;
 listen [::]:80;
 server_name search.example.com;
 # ACME challenge pass-through
 location /.well-known/acme-challenge/ { root /var/www/letsencrypt; }
 # Everything else forced to HTTPS
 location / { return 301 https://$host$request_uri; }
}

server {
 listen 443 ssl http2;
 listen [::]:443 ssl http2;
 server_name search.example.com;

 # Certificates & TLS hardening
 ssl_certificate /etc/letsencrypt/live/search.example.com/fullchain.pem;
 ssl_certificate_key /etc/letsencrypt/live/search.example.com/privkey.pem;
 ssl_protocols TLSv1.2 TLSv1.3;
 ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
 ssl_prefer_server_ciphers off;
 ssl_session_cache shared:SSL:10m;
 ssl_session_timeout 10m;

 # Security headers
 add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
 add_header X-Content-Type-Options nosniff;
 add_header X-Frame-Options DENY;
 add_header Referrer-Policy strict-origin-when-cross-origin;
 add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';";

 # Access control: Basic Auth (production: replace with Authelia/OAuth2-Proxy)
 auth_basic "SearXNG Private Instance";
 auth_basic_user_file /etc/nginx/.htpasswd_searxng;

 # Static assets long-term cache
 location /static/ {
 alias /var/lib/docker/volumes/searxng_searxng_data/_data/static/; # mounted volume static dir
 expires 1y;
 add_header Cache-Control "public, immutable";
 access_log off;
 }

 # Dynamic proxy
 location / {
 limit_req zone=searxng_limit burst=20 nodelay;
 limit_req zone=searxng_burst burst=50 nodelay;
 proxy_pass http://searxng_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;
 proxy_set_header X-Forwarded-Host $host;
 proxy_set_header X-Forwarded-Port 443;
 proxy_http_version 1.1;
 proxy_set_header Connection "";
 proxy_buffering off;
 proxy_request_buffering off;
 proxy_read_timeout 30s;
 proxy_send_timeout 30s;
 # Pass real client IP to SearXNG for limiter decisions
 proxy_set_header Forwarded "for=$remote_addr; proto=$scheme; host=$host";
 }

 # Health check pass-through (no rate limit, no auth)
 location = /healthz {
 access_log off;
 proxy_pass http://searxng_backend/healthz;
 }

 # Prometheus metrics only reachable from monitoring network
 location = /metrics {
 allow 10.0.0.0/8; # example: monitoring subnet
 allow 172.16.0.0/12;
 deny all;
 proxy_pass http://searxng_backend/metrics;
 }
}

Key Point Analysis:

  1. Dual-layer rate limiting: Two limit_req_zone definitions — searxng_limit smooths steady traffic, searxng_burst absorbs spikes; nodelay ensures burst-bucket requests forward with zero latency, excess returns 503 immediately.
  2. Real IP passthrough: X-Real-IP + Forwarded header double insurance. SearXNG reads X-Forwarded-For first value for request.remote_addr; enable use_forwarded_for: true in settings.yml (default on).
  3. Static asset offload: /static/ maps directly to host volume path (verify with docker compose exec searxng find /var/lib/searxng -name static), bypassing uWSGI, reducing Python context switches.
  4. Health & metrics isolation: /healthz shared by Nginx proxy_next_upstream and Docker healthcheck; /metrics restricted to monitoring CIDRs, preventing internal state leakage.

Caddy Alternative: If you prefer zero-config TLS, a Caddyfile achieves all above in ~10 lines (auto ACME, rate limiting, Basic Auth, static file serving). Nginx still holds a slight edge in high-concurrency connection reuse & memory footprint, plus a more mature ecosystem (ModSecurity, OpenResty).

Advanced Access Control: From Basic Auth to Zero-Trust Gateway

The tutorial only demonstrates htpasswd generating .htpasswd for Nginx. For team collaboration, multi-device sync, audit compliance — strongly recommend Authelia or OAuth2-Proxy:

  • Authelia: Deploy as standalone container, integrates LDAP/AD/OIDC, provides TOTP/WebAuthn 2FA, device trust, risk scoring. Nginx uses auth_request /authelia/verify to proxy auth result, passes Remote-User, Remote-Groups headers back to SearXNG for role-based engine visibility control.
  • OAuth2-Proxy: Lightweight, supports GitHub/Google/GitLab/OIDC login, email_domains allowlist restricts to org members. Nginx auth_request points to oauth2-proxy:4180; after login, encrypted cookie set, subsequent requests .

Migration Path: Keep Nginx Basic Auth as fallback, add auth_request as primary; test with staging subdomain before cutting over.

Upstream Engine Rate Limiting & Health Governance

Even with proxy-layer limiting, SearXNG’s own outbound concurrency can trigger upstream bans. Two-layer defense:

  1. settings.yml per-engine throttling (see engines section above): rate_limit: 1.0 ensures ≥1 second gap between requests to same engine from this instance.
  2. Host-level tc / nftables egress shaping (optional but powerful): Cap outbound TCP connections to known search engine ASNs at 50 concurrent, 200/minute. Example nft rule:
nft add rule ip filter output ip daddr { 142.250.0.0/16, 204.79.197.0/24 } counter limit rate 200/minute accept

Adjust CIDRs to actual upstream IP ranges (periodically refresh via dig). 3. Automated health checks: SearXNG exposes /healthz (liveness) and per-engine status via /api/engines. Write a systemd timer (runs every 15 min) that:

  • Calls /api/engines, parses JSON for engine.status != "online".
  • Auto-disables failing engines via settings.yml patch + SIGHUP reload.
  • Alerts via webhook (Telegram/Slack/email) when >2 core engines down.

Observability Stack: Logs, Metrics, Tracing

Layer Tooling Key Dashboards / Alerts
Container Logs Docker JSON driver (max-size=10m,max-file=5) → Loki / Vector → Grafana Error rate > 5%/5m, uWSGI harakiri triggers, OOM kills
Application Metrics /metrics (Prometheus format) → Prometheus → Grafana searxng_requests_total by engine/status, searxng_request_duration_seconds p95 > 3s, searxng_engine_errors_total spike
Infrastructure Node Exporter + cAdvisor → Prometheus CPU > 80% 5m, Memory > 85%, Disk > 80%, Network saturation
Synthetic Monitoring Blackbox Exporter prober → /healthz + /search?q=test HTTP 200 < 99.9% over 24h, latency p99 > 5s
Distributed Tracing (optional) OpenTelemetry Python auto-instrument → Jaeger End-to-end latency breakdown: proxy → uWSGI → upstream HTTP → template render

Grafana Dashboard JSON (import ID 19847 or build custom): panels for QPS by engine, error heatmap, cache hit ratio (if Redis enabled), active uWSGI workers, queue depth.

Backup, Disaster Recovery & Migration Drills

What to Back Up (daily, encrypted, off-site):

  • /etc/searxng/settings.yml (contains secret_key — loss = all sessions invalidated)
  • /var/lib/searxng/ volume (custom templates, static overrides, instance SQLite if used)
  • Nginx configs (/etc/nginx/sites-available/search.example.com, .htpasswd_searxng)
  • Certbot /etc/letsencrypt/ (or ACME account keys if using DNS-01)

Backup Script (run via systemd timer searxng-backup.timer):

#!/usr/bin/env bash
set -euo pipefail
DATE=$(date +%F-%H%M)
DEST="/srv/backups/searxng/$DATE"
mkdir -p "$DEST"
docker compose cp searxng:/etc/searxng/settings.yml "$DEST/settings.yml"
tar -czf "$DEST/searxng_data.tar.gz" -C /var/lib/docker/volumes/searxng_searxng_data/_data .
cp /etc/nginx/sites-available/search.example.com "$DEST/nginx.conf"
cp /etc/nginx/.htpasswd_searxng "$DEST/htpasswd"
# Encrypt with age/sops before uploading to S3/Backblaze B2
age -r "$AGE_PUBLIC_KEY" -o "$DEST.tar.gz.age" "$DEST.tar.gz"
rclone copy "$DEST.tar.gz.age" remote:searxng-backups/
# Retain 30 days local, 90 days remote
find /srv/backups/searxng -type f -mtime +30 -delete
rclone delete --min-age 90d remote:searxng-backups/

Restore Drill (quarterly, documented runbook):

  1. Provision fresh VPS (same OS, Docker, Compose).
  2. Pull pinned image searxng/searxng:2026.11.0.
  3. Decrypt latest backup, extract settings.yml & volume tarball.
  4. docker compose up -d, verify /healthz + test query.
  5. Swap DNS A record, confirm TLS cert issuance (or restore Certbot dir).
  6. Record RTO/RPO; target < 15 min RTO, < 24 h RPO.

Systemd Service Management (Host-Level)

While Compose handles container lifecycle, wrapping it in a systemd unit enables boot ordering, journal integration, and systemctl U

Sources & References

Spotted outdated pricing, stock, or expired coupons?See methodology & report an update →

Related articles