Claude API Docker Container Deployment Tutorial
Deploying an app that talks to the Claude API inside Docker is mostly about getting three things right: a small, reproducible image, secure handling of API keys at runtime, and a container that behaves well under restarts and scaling. This tutorial walks through a working Dockerfile for a Node.js service that calls Claude, explains where people get secrets management wrong, and shows a docker-compose setup you can copy for local dev or a small VPS deployment.
If you're containerizing a Claude-powered backend, the actual API calls don't change — you still send HTTPS requests to Anthropic's (or a gateway's) endpoint. What changes is how your app gets its credentials, how it handles network timeouts inside an isolated runtime, and how you keep the image lean enough to deploy fast. Below is a complete, minimal setup you can adapt.
A minimal Claude API service to containerize
Start with a small Express app that proxies a chat request to Claude:
// server.js
import express from "express";
const app = express();
app.use(express.json());
app.post("/chat", async (req, res) => {
try {
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": process.env.CLAUDE_API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: req.body.messages,
}),
});
const data = await response.json();
res.json(data);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(process.env.PORT || 3000, () => {
console.log("Claude proxy running");
});
Nothing special here — the important part is that CLAUDE_API_KEY is read from the environment, never hardcoded.
Writing the Dockerfile
Use a multi-stage build so the final image doesn't carry build tools or dev dependencies:
# ---- build stage ----
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
# ---- runtime stage ----
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app /app
USER node
EXPOSE 3000
CMD ["node", "server.js"]
A few things matter here that get skipped in a lot of tutorials:
- Alpine base keeps the image small (under 100MB typically), which speeds up deploys and reduces attack surface.
USER nodedrops root privileges inside the container — don't run your Claude proxy as root.- No
.envfile copied into the image. Secrets go in at runtime, not build time.
Add a .dockerignore:
node_modules
.env
.git
*.log
Passing the API key safely
Never bake CLAUDE_API_KEY into the image with ENV in the Dockerfile — anyone with access to the image can extract it with docker history or by inspecting layers. Instead, inject it at docker run time:
docker build -t claude-proxy .
docker run -d \
-p 3000:3000 \
-e CLAUDE_API_KEY="sk-ant-xxxxx" \
--name claude-proxy \
claude-proxy
For orchestrated environments, use your platform's secrets manager (Docker Swarm secrets, Kubernetes Secret objects, or your cloud provider's secret store) and mount it as an environment variable or file at startup rather than passing it as a plain CLI flag in CI logs.
docker-compose for local development
If your service depends on other containers (a database, a cache, a queue), compose makes local testing much easier:
version: "3.9"
services:
app:
build: .
ports:
- "3000:3000"
environment:
- CLAUDE_API_KEY=${CLAUDE_API_KEY}
- PORT=3000
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"]
interval: 30s
timeout: 5s
retries: 3
Store CLAUDE_API_KEY in a local .env file (not committed to git) and compose will pick it up automatically via ${CLAUDE_API_KEY} interpolation.
Handling timeouts and retries inside the container
Claude API calls can take longer than typical REST requests, especially with large max_tokens or long context. Inside a container, this interacts badly with default proxy or load balancer timeouts. Two things to set explicitly:
- Application-level timeout — set a reasonable
fetch/HTTP client timeout (30–60s for non-streaming, longer for streaming) rather than relying on defaults. - Reverse proxy timeout — if you're running Nginx or Traefik in front of the container, raise
proxy_read_timeoutto match, or responses will get cut off mid-stream.
If you're using streaming responses, make sure your container's HTTP server doesn't buffer the whole response before sending — this is a common cause of "streaming that isn't actually streaming" once deployed behind a proxy.
Skipping the plumbing with a hosted API layer
Building and maintaining this proxy — key rotation, per-user rate limits, usage tracking, retry logic for streaming — adds up once you have more than one consumer of your Claude access. SubToAPI turns your existing Claude access into a clean HTTPS API with application keys (sub_live_...), streaming, tool use, and usage metadata already built in, so your Docker container just calls one stable endpoint instead of reimplementing all of this.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Summarize this ticket"}]
}'
That means your Dockerfile and compose setup above barely change — you just swap the endpoint and pass SUBTOAPI_KEY the same way you'd pass CLAUDE_API_KEY. See the quickstart for the full request/response shapes, streaming for SSE details, and tools if your containerized service needs function calling. Plans start at pricing, with a free trial at signup.
Deployment checklist
- Multi-stage Dockerfile, non-root user,
.dockerignoreexcluding secrets. - API key injected via environment variable or secrets manager at runtime, never built into the image.
- Explicit HTTP client and reverse proxy timeouts tuned for LLM response latency.
- Health check endpoint so your orchestrator knows when the container is actually ready.
- Logs sent to stdout/stderr so your container platform can collect them — don't write logs to disk inside the container.
questions
Do I need a different Dockerfile for streaming responses vs. regular requests? No — the same container works for both. The difference is in your app code (using SSE) and your reverse proxy config (disabling response buffering), not the image itself.
Should I store my Claude API key in the image for simplicity? No. Baking secrets into Docker layers makes them extractable by anyone with image access. Always inject keys at container runtime via environment variables or a secrets manager.
Can I run a Claude API proxy container on a serverless platform instead of a VM? Yes — most container-based serverless platforms (Cloud Run, ECS Fargate, Fly.io) run this same Dockerfile unmodified. Just make sure your timeout settings match the platform's request duration limits.