Claude Code with Docker
Why Docker and Claude Code work well together
Docker is configuration-heavy and error-prone. Dockerfiles, compose files, networking, volumes, multi-stage builds: there's a lot of boilerplate that follows predictable patterns. That's exactly where AI coding tools excel.
Claude Code understands Docker deeply. It reads your project structure, determines the right base image, configures build stages, sets up compose services, and debugs container issues, all from your terminal. No context-switching to Docker documentation or Stack Overflow.
This guide covers the practical workflows for using Claude Code with Docker across development, debugging, and CI/CD.
Generating Dockerfiles
Start with your project. Claude Code reads your package.json, requirements.txt, go.mod, or whatever dependency manifest you have, and generates a Dockerfile that actually works for your stack.
Create a production Dockerfile for this Next.js app.
Multi-stage build, minimal final image, non-root user.
Claude Code produces something like:
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm build
FROM node:20-alpine AS runner
WORKDIR /app
RUN addgroup --system app && adduser --system --ingroup app app
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
USER app
EXPOSE 3000
CMD ["node", "server.js"]
Multi-stage builds, minimal attack surface, non-root execution. Claude Code applies these patterns by default because they're the right way to containerize applications. It doesn't generate the naive single-stage Dockerfiles you find in "getting started" tutorials.
The key is giving Claude Code context about your requirements. Tell it about your constraints:
This runs on AWS ECS with 512MB memory limit. The build
also needs to work in GitHub Actions with layer caching.
Now it optimizes layer ordering for cache efficiency and keeps the final image lean.
Docker Compose workflows
Real development environments need multiple services. Claude Code builds compose files that match your actual architecture:
Set up docker-compose for local development:
- Next.js app with hot reload
- PostgreSQL 16 with persistent volume
- Redis for caching
- Mailhog for email testing
Claude Code generates the full docker-compose.yml with correct networking, volume mounts, health checks, and dependency ordering. It knows that your app needs to wait for Postgres to be healthy before starting, and it configures that with depends_on and health checks, not the fragile sleep 5 pattern.
Development vs. production compose files
Claude Code understands the split. Ask it to create both:
I need a docker-compose.dev.yml for local development
(hot reload, debug ports, volume mounts) and a
docker-compose.prod.yml for deployment (built images,
resource limits, restart policies).
The dev version mounts your source code as a volume for hot reload. The prod version uses built images with resource constraints. Claude Code handles the override pattern so docker compose -f docker-compose.yml -f docker-compose.dev.yml up works correctly.
Debugging container issues
This is where Claude Code saves the most time. Container debugging is notoriously frustrating, the error happens inside a layer you can't see, or the container exits before you can inspect it.
Build failures
Paste your build error and Claude Code diagnoses it:
My Docker build fails at step 7 with "npm ERR! ERESOLVE
unable to resolve dependency tree". Here's the Dockerfile.
Claude Code reads your Dockerfile, identifies the issue (usually a lockfile mismatch or missing --legacy-peer-deps), and fixes it. It understands the relationship between your host lockfile, the COPY order, and the install step.
Runtime crashes
When containers start and immediately exit:
The container starts but exits with code 137.
Logs show nothing useful.
Exit code 137 means OOM kill. Claude Code knows this and suggests either increasing the memory limit or optimizing your application's memory usage. It reads your Dockerfile to check for common memory issues, missing garbage collection flags, unbounded caches, or missing swap configuration.
Networking issues
Container A can't reach container B on port 5432.
They're in the same compose file.
Claude Code checks your compose networking configuration, service names, exposed ports vs. published ports, and custom network definitions. The fix is usually a service name mismatch or a port binding error.
For complex debugging sessions, Claude Code's memory systems let you persist container configuration patterns so you don't re-diagnose the same issues across sessions.
CI/CD with Docker and Claude Code
Claude Code generates CI/CD pipelines that build, test, and deploy containers to platforms like AWS ECS, Railway, or Google Cloud Run. It understands the nuances of Docker in CI environments, layer caching, registry authentication, and multi-platform builds.
GitHub Actions pipeline
Create a GitHub Actions workflow that:
- Builds the Docker image on push to main
- Runs tests inside the container
- Pushes to ECR if tests pass
- Deploys to ECS with rolling update
Claude Code generates the full workflow with proper caching:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
It uses GitHub Actions cache for Docker layers, which can cut build times from minutes to seconds on subsequent runs.
Multi-platform builds
Need ARM and AMD64 images for mixed infrastructure:
The image needs to run on both x86 EC2 instances and
ARM-based Graviton instances.
Claude Code configures Buildx with QEMU for cross-compilation, sets up the platform matrix, and handles the manifest list so a single tag works on both architectures.
Docker security hardening
Claude Code applies security best practices when you ask for them:
Harden this Dockerfile for production. Assume it runs
in a multi-tenant Kubernetes cluster.
It addresses the key concerns:
- Non-root user: creates a dedicated user and switches before
CMD - Read-only filesystem: sets appropriate mount points for writable paths
- No unnecessary packages: uses
--no-install-recommendsand cleans caches - Pinned versions: locks base image digests, not just tags
- Secret handling: uses build secrets or runtime injection, never
ARGfor credentials - Minimal base: switches to
distrolessoralpinewhere possible
Docker with Claude Code hooks
You can integrate Docker into your Claude Code workflow using hooks. For example, a pre-commit hook that validates your Dockerfile:
{
"hooks": {
"PreCommit": [{
"command": "docker build --check . 2>&1 || echo 'Dockerfile lint failed'",
"description": "Validate Dockerfile before commit"
}]
}
}
Or a post-task hook that rebuilds containers after dependency changes:
{
"hooks": {
"PostToolUse": [{
"command": "if echo '$INPUT' | grep -q 'package.json'; then docker compose build app; fi",
"description": "Rebuild container when dependencies change"
}]
}
}
This keeps your containers in sync with code changes automatically.
Optimizing image size
Large images slow down deployments and increase costs. Claude Code aggressively optimizes when asked:
This image is 1.2GB. Get it under 200MB without
breaking functionality.
Common fixes Claude Code applies:
- Switch to Alpine or distroless base images
- Multi-stage builds to exclude build tools from final image
- Remove test files, documentation, and source maps
- Use
.dockerignoreto excludenode_modules,.git, and test fixtures - Combine
RUNlayers to reduce intermediate layers - Clean package manager caches in the same layer as install
The result is typically a 5-10x reduction in image size with no functional changes.
Managing Docker environments with CLAUDE.md
Document your Docker setup in CLAUDE.md so Claude Code understands your containerized architecture from the start of every session:
## Docker
- Development: `docker compose up` (uses docker-compose.dev.yml)
- Production images: multi-stage, pushed to ECR
- Base images: node:20-alpine for JS, python:3.12-slim for Python
- All services use health checks
- Secrets injected via environment, never baked into images
This eliminates the back-and-forth where Claude Code asks about your Docker setup. It reads this once and applies your conventions for the entire session. For more on configuring your project, check our project setup guide.
FAQ
Can Claude Code run Docker commands directly?
Yes. Claude Code can execute docker build, docker compose up, docker logs, and any other Docker CLI command directly in your terminal. It reads the output and adjusts its approach based on what it sees, building, debugging, and iterating in a single conversation.
How do I handle Docker secrets with Claude Code?
Never put secrets in Dockerfiles or compose files that get committed. Use environment variables injected at runtime, Docker secrets for Swarm/Kubernetes, or build-time secrets with --mount=type=secret. Tell Claude Code your secret management approach in CLAUDE.md and it will follow that pattern in all generated Docker configs.
Should I use Claude Code inside a Docker container?
You can run Claude Code inside a container for isolated development environments. Use the official installation and mount your project directory as a volume. This is useful for teams that want consistent tooling without local installation, though it adds a layer of indirection for file access and terminal interaction.
Get Claudify, Docker-ready project templates, CI/CD workflows, and production-tested commands. One command to install: npx create-claudify.
More like this
Ready to upgrade your Claude Code setup?
Get Claudify