When deploying an AI-powered web app, calling an LLM provider directly from the browser leaks your API key—and spinning up a bare HTTP backend on a VPS without rate limits invites runaway token bills the moment a scraper discovers your endpoint.
In this step-by-step guide, we will put a lightweight Caddy reverse proxy in front of a containerized Node.js HTTP API service using Docker Compose, giving you:
- Automatic Let's Encrypt HTTPS certificates with zero manual renewal
- Clean request-body size limits (preventing oversized payload abuse)
- Strict security headers and structured JSON access logs
Architecture Overview
Client (HTTPS :443)
└──> Caddy Container (Auto-TLS + Security Headers + Body Limit)
└──> Internal Docker Network (no public port exposed)
└──> AI Proxy API Container (:3000)
└──> Upstream LLM / API Provider (with env secret)
Only Caddy binds to ports 80 and 443; the backend API container stays isolated on Docker's internal network.
Step 1: Project Layout
mkdir -p ~/ai-proxy-stack/api
cd ~/ai-proxy-stack
ai-proxy-stack/
├── docker-compose.yml
├── Caddyfile
├── .env
└── api/
├── Dockerfile
└── server.mjs
Step 2: Minimal Streaming-Safe API Service (api/server.mjs)
import http from "node:http";
const PORT = Number(process.env.PORT || 3000);
const WINDOW_MS = 60_000;
const MAX_REQUESTS_PER_WINDOW = 20;
const buckets = new Map();
function isRateLimited(ip) {
const now = Date.now();
const timestamps = (buckets.get(ip) || []).filter((t) => now - t < WINDOW_MS);
if (timestamps.length >= MAX_REQUESTS_PER_WINDOW) {
buckets.set(ip, timestamps);
return true;
}
timestamps.push(now);
buckets.set(ip, timestamps);
return false;
}
const server = http.createServer((req, res) => {
if (req.url === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ status: "ok" }));
}
const clientIp =
req.headers["x-forwarded-for"]?.toString().split(",")[0].trim() ||
req.socket.remoteAddress ||
"unknown";
if (isRateLimited(clientIp)) {
res.writeHead(429, { "Content-Type": "application/json", "Retry-After": "60" });
return res.end(JSON.stringify({ error: "Rate limit exceeded. Try again shortly." }));
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, clientIp }));
});
server.listen(PORT, "0.0.0.0", () => {
console.log(`API proxy listening on :${PORT}`);
});
Create api/Dockerfile:
FROM node:22-alpine
WORKDIR /app
COPY server.mjs ./
USER node
EXPOSE 3000
CMD ["node", "server.mjs"]
Step 3: Automatic HTTPS & Payload Limits (Caddyfile)
api.example.com {
encode zstd gzip
request_body {
max_size 1MB
}
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
-Server
}
reverse_proxy api:3000 {
flush_interval -1
}
log {
output stdout
format json
}
}
Setting flush_interval -1 disables response buffering so Server-Sent Events (SSE) and LLM token streams reach the browser immediately.
Step 4: Orchestrate with docker-compose.yml
services:
caddy:
image: caddy:2-alpine
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data
- caddy_config:/config
depends_on:
api:
condition: service_healthy
api:
build: ./api
restart: unless-stopped
env_file:
- .env
expose:
- "3000"
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"]
interval: 15s
timeout: 3s
retries: 3
volumes:
caddy_data:
caddy_config:
Launch and verify:
docker compose up -d --build
curl -i https://api.example.com/health
Key Production Checks
- Swap in-memory rate limits for Redis if you scale past one container.
-
Verify
429 Too Many Requestsby firing 25 rapidcurlcalls and checkingRetry-After. -
Never commit
.env—keep upstream AI keys strictly server-side.
More AI engineering and infrastructure notes on X at @PhuHo420785.
Top comments (0)