Claude API Docker Deployment Best Practices
Deploying an application that calls the Claude API inside Docker is mostly a question of handling secrets, network reliability, and process lifecycle correctly — the Claude API itself is just an HTTPS endpoint, so the container doesn't need anything exotic. The best practices come down to: never bake keys into images, make outbound calls resilient to retries and timeouts, keep containers stateless, and design health checks that reflect real API availability, not just "the process is running."
This guide walks through a production-grade setup for containerizing a service that talks to Claude (or a Claude-compatible gateway like SubToAPI), covering image design, secret management, networking, observability, and common failure modes.
Image Design: Keep It Small and Stateless
Your container should contain only your application code and runtime — no API keys, no cached conversation state that can't survive a restart.
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
FROM node:20-alpine
WORKDIR /app
COPY --from=build /app .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]
Key points:
- Multi-stage builds keep the final image small, which speeds up deploys and reduces attack surface.
- Run as a non-root user (
USER node) — API credentials in environment variables are more exposed if a container is compromised with root access. - Don't cache conversation history inside the container's filesystem. If you need persistence, use an external store (Redis, Postgres) so any container instance can be killed and replaced without losing state.
Secrets: Never Bake Keys Into the Image
The most common mistake is COPY .env .env or hardcoding ANTHROPIC_API_KEY=sk-... in a Dockerfile. Anyone who pulls the image gets the key.
Instead:
- Pass keys at runtime via
docker run -eor your orchestrator's secret manager (Kubernetes Secrets, AWS Secrets Manager, Docker Swarm secrets). - Use
.dockerignoreto exclude.envfiles from the build context entirely. - Rotate keys on a schedule and whenever a container image or registry is exposed publicly.
docker run -d \
--name claude-service \
-e SUBTOAPI_KEY="$SUBTOAPI_KEY" \
-p 3000:3000 \
your-registry/claude-service:latest
If you're managing multiple environments (staging, production, per-customer deployments), scoping keys per environment matters more than most teams realize — a leaked staging key shouldn't have production-level spend limits. SubToAPI's dashboard lets you issue separate sub_live_... keys per team or project so a compromised staging container doesn't expose production usage. See /docs/quickstart for key setup.
Networking: Timeouts, Retries, and DNS
Containers are more sensitive to transient network issues than bare-metal processes, especially in orchestrated environments where DNS resolution and outbound routing can be flaky during scale-up events.
- Set explicit timeouts on every outbound call to the API. Don't rely on the default socket timeout, which can hang for minutes.
- Implement exponential backoff with jitter for 429s and 5xxs — this is the same strategy you'd use against any rate-limited API.
- Resolve DNS at request time, not just once at startup, especially behind load balancers or CDNs that rotate IPs.
async function callAPI(payload, retries = 3) {
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(15000)
});
if (res.status === 429 || res.status >= 500) throw new Error(`Retryable: ${res.status}`);
return res;
} catch (err) {
if (attempt === retries) throw err;
await new Promise(r => setTimeout(r, 2 ** attempt * 500 + Math.random() * 300));
}
}
}
Health Checks That Actually Mean Something
A Docker HEALTHCHECK that just pings / on your own server doesn't tell you anything about whether your app can actually reach the Claude API. For services where that connectivity is core to functionality, add a lightweight check that hits a cheap endpoint (not a full completion request — that burns tokens and money).
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD curl -f http://localhost:3000/healthz || exit 1
Inside /healthz, check API reachability without making a billable call — for example, cache the result of a lightweight connectivity check on a short interval rather than re-verifying on every health probe.
Scaling and Rate Limits
If you run multiple container replicas behind a load balancer, they all share the same upstream rate limit unless you're using separate keys per replica or per tenant. Two practical approaches:
- Centralize rate limiting at a gateway layer so replicas don't independently retry into the same 429 wall.
- Use separate API keys per service or team so one noisy container doesn't throttle everyone else. This is one of the reasons teams move off raw Anthropic console keys to a system with per-key scoping — see /docs for how SubToAPI structures keys per project.
For streaming responses specifically, make sure your reverse proxy (nginx, Envoy, ALB) has timeouts long enough for Server-Sent Events, and disable response buffering — a default proxy buffer will swallow partial SSE chunks. Details on streaming behavior are in /docs/streaming.
Logging and Observability
Container logs should capture request IDs, latency, and token usage without logging full prompt or response content (which may contain sensitive user data and bloats log storage). Structure logs as JSON so they're queryable in your aggregation tool:
{"ts":"2024-01-15T10:22:01Z","event":"api_call","model":"claude-sonnet","latency_ms":820,"status":200,"tokens_in":412,"tokens_out":189}
If you need per-project cost visibility across containers, pulling usage metadata from the API response (or from a dashboard like SubToAPI's, which tracks usage per key) is more reliable than trying to reconstruct spend from logs after the fact.
CI/CD Checklist
- Build images in CI, never locally push to production registries.
- Scan images for vulnerabilities before deploy (
docker scanor Trivy). - Inject secrets via your CI/CD secret store at deploy time, not at build time.
- Tag images with git SHA, not
latest, for reproducible rollbacks. - Run a smoke test against a real (low-cost) API call in staging before promoting to production.
questions
Do I need a different Docker setup for streaming vs. non-streaming Claude API calls? Not structurally, but your reverse proxy and load balancer need longer timeouts and buffering disabled for streaming responses. The container itself doesn't change — see /docs/streaming for client-side handling details.
Should I store the API key as a Docker build arg or a runtime environment variable? Always runtime. Build args can leak into image layers and are visible via docker history. Pass keys with -e at docker run time or through your orchestrator's secret manager.
How do I avoid hitting rate limits when scaling container replicas horizontally? Use a shared rate-limiting layer in front of your replicas, or assign separate scoped API keys per service so one replica's load doesn't throttle the others. Check /pricing for plans that support multiple team-scoped keys.