Claude API Self-Hosted Proxy with Docker: A Guide
What people actually mean by "self-hosted Claude API proxy"
If you're searching for this, you're probably trying to put something in front of the raw Anthropic API: a service you control that holds the real Claude API key, exposes a simpler or safer endpoint to your apps, and runs in a container you deploy yourself (Docker, Docker Compose, Kubernetes, whatever). Common reasons: you want to hide the Anthropic key from client code, add logging or rate limiting, cache responses, or give multiple internal services a single internal endpoint instead of scattering the real key everywhere.
The short answer: yes, this is straightforward to build — a reverse proxy is maybe 80 lines of Node or Python — but "straightforward to build" and "safe to run in production" are different claims. Below is a working pattern you can containerize today, plus the operational pieces (TLS, key rotation, streaming, rate limits, logging) that turn a weekend script into something you'd trust with real traffic. If you decide the ops overhead isn't worth it, a managed option like SubToAPI does the same job without the container to maintain.
What the proxy needs to do
At minimum, a Claude API proxy container needs to:
- Accept requests from your internal services on a simple path (e.g.
/v1/messages) - Attach the real Anthropic API key server-side, never exposing it to callers
- Forward the request body unchanged (or transformed) to
api.anthropic.com - Stream the response back if the client requested streaming
- Log request metadata (latency, token usage, status) without logging full prompt content if you have privacy requirements
- Enforce whatever access control you want on your own callers (internal API keys, IP allowlists, per-service rate limits)
That's the whole job. Everything else — retries, caching, multi-provider routing — is optional complexity layered on top.
A minimal proxy you can containerize
Here's a basic Express-based proxy. It takes requests with your own internal bearer token, injects the real Claude key, and streams the response through.
// server.js
import express from "express";
import fetch from "node-fetch";
const app = express();
app.use(express.json({ limit: "2mb" }));
const INTERNAL_TOKEN = process.env.PROXY_INTERNAL_TOKEN;
const CLAUDE_API_KEY = process.env.ANTHROPIC_API_KEY;
app.post("/v1/messages", async (req, res) => {
if (req.headers.authorization !== `Bearer ${INTERNAL_TOKEN}`) {
return res.status(401).json({ error: "unauthorized" });
}
const upstream = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": CLAUDE_API_KEY,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify(req.body),
});
res.status(upstream.status);
upstream.body.pipe(res);
});
app.listen(8080, () => console.log("proxy listening on 8080"));
Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV PORT=8080
EXPOSE 8080
CMD ["node", "server.js"]
And a docker-compose.yml to run it with secrets kept out of the image:
services:
claude-proxy:
build: .
ports:
- "8080:8080"
environment:
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
- PROXY_INTERNAL_TOKEN=${PROXY_INTERNAL_TOKEN}
restart: unless-stopped
This is enough to get a working proxy behind docker compose up. It is not enough for production without a few additions.
What you take on once this is running
A self-hosted proxy container is simple at first and accretes requirements fast:
- TLS termination. You'll need a reverse proxy (Caddy, Traefik, nginx) or a load balancer in front of the container — Claude clients should never talk to the proxy over plain HTTP.
- Streaming correctness. Server-Sent Events need careful handling of buffering, timeouts, and connection keep-alive. A naive
pipe()works for small payloads but breaks under load balancers that buffer responses. - Key rotation. If the Anthropic key is compromised or you rotate on a schedule, you need a deployment process that updates the secret and restarts containers without downtime.
- Rate limiting and quotas. Anthropic enforces its own rate limits upstream; you likely want your own per-caller limits too, which means adding Redis or an in-memory store and more code.
- Usage visibility. Token counts and cost tracking require parsing response metadata and persisting it somewhere queryable — another service, another container.
- Multi-tenant auth. If more than one team or app calls the proxy, "one shared internal token" quickly becomes a liability. You end up building a mini API-key system: issuing, scoping, and revoking keys per caller.
None of this is hard individually. Collectively it's a small internal product that someone has to own, patch, and keep running.
When to self-host vs. use a managed proxy
Self-hosting makes sense when you have strict data residency requirements, need custom request transformation that a managed service won't support, or already run the infrastructure (Kubernetes, service mesh, secrets manager) to operate this kind of container without extra headcount.
It makes less sense when the real goal was just "don't put the raw Anthropic key in client code" and "give my team a usable API with usage tracking." That's exactly what SubToAPI is built for: it turns your existing Claude access into an HTTPS API with scoped sub_live_... application keys, streaming, tool use, and per-key usage metadata — without you running a container at all. You create a key in the dashboard, swap the endpoint, and you're done:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Summarize this proxy pattern"}]
}'
See the quickstart, messages, streaming, and tool use docs for the full request shape, and pricing if you want to compare the cost of a managed key against the cost of running and maintaining your own proxy container.
Questions
Can I run a Claude API proxy in Docker without exposing my Anthropic key to clients? Yes — that's the main use case. The container holds the real key as an environment variable or mounted secret, and callers only see your internal token. Make sure the key never ends up in logs, error messages, or client-visible response headers.
Does a self-hosted proxy support streaming responses? It can, but you have to implement it carefully — avoid reverse proxies or load balancers that buffer the response body, and use a client library or raw fetch that supports chunked transfer encoding end to end.
Is self-hosting cheaper than a managed Claude API proxy? Only if you ignore the cost of building and maintaining it. Compute for a small proxy container is cheap, but engineering time for TLS, key rotation, rate limiting, and usage tracking usually exceeds the price of a managed plan like SubToAPI's once more than one team depends on it.