Docker Prompts: 20 Proven AI Prompts for Dockerfile, Compose & Container Optimization
If you've ever struggled with a bloated Docker image, a mysteriously crashing container, or a Compose file that refuses to start, you already know the pain. Docker is powerful, but its steep learning curve costs teams hours every week. The good news: modern AI assistants — ChatGPT, Claude, Gemini, and code-focused tools like Cursor — can handle entire Docker workflows if you ask the right questions.
This is exactly why I've collected the most effective Docker prompts from my own workflow. They cover Dockerfile generation, multi-stage builds, Docker Compose architecture, image size optimization, debugging, and security hardening. Every prompt is written in a production-ready way and can be copy-pasted into any AI tool.
Use this guide as a cheat sheet: pick a prompt, adapt it to your stack, and let the AI handle the repetitive part. By the end, you'll have a repeatable system for building lean, secure, and reliable containerized applications.
1. Dockerfile Prompts: Generate Solid Images From Scratch
The Dockerfile is the foundation of everything. A good prompt saves you from the most common mistakes: trailing spaces, missing healthchecks, the wrong base image tag, or unnecessary root privileges.
1.1. Generate a Production-Ready Dockerfile
The most versatile prompt in this entire collection. It gives you a complete, production-ready Dockerfile with a non-root user, healthcheck, and pinned dependencies.
Prompt: "Generate a production-ready Dockerfile for a Python 3.12 FastAPI application that uses
pipandrequirements.txt. Use a multi-stage build, run the service as a non-root user, expose port 8000, add a/healthhealthcheck, and use a minimal base image. Also suggest the matching.dockerignore."
Why this works: the AI knows you want not just "a" Dockerfile but a hardened one. Asking for a non-root user and a healthcheck automatically forces best practices.
Result example:
# Stage 1: build dependencies
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
# Stage 2: runtime
FROM python:3.12-slim
RUN useradd --create-home appuser
WORKDIR /app
COPY --from=builder /install /usr/local
COPY app.py .
USER appuser
EXPOSE 8000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
For Node.js, Go, or Ruby, just swap the runtime name and package manager. The AI already knows the pattern.
1.2. Multi-Stage Build for Microservices
Multi-stage builds are the single biggest win for final image size. Instead of explaining the concept, let the AI do the drafting.
Prompt: "Write a multi-stage Dockerfile for a Node.js 20 TypeScript microservice. Stage 1: install dependencies and run
npm run build. Stage 2: copy onlydist/andnode_modules --omit=devinto a slim production image. Use a non-root Node user, setNODE_ENV=production, and add a gzip compression layer for static assets."
This prompt is especially useful for teams migrating from a monolithic Dockerfile to microservices — it forces the AI to separate build-time and runtime, which is exactly what production isolation should look like.
1.3. Optimize Layer Caching in an Existing Dockerfile
Sometimes you don't need a new Dockerfile — you need fixes. AI is surprisingly good at spotting cache-breaking mistakes like copying all files before installing dependencies.
Prompt: "Here is my Dockerfile: [paste the code]. Analyze it for layer caching issues: which RUN commands invalidate the cache, which COPY commands run too early, and how can I reorder it to make rebuilds faster? Return the optimized Dockerfile with a brief explanation of each change."
Instant value: developers often copy package.json and package-lock.json together with the whole application code. Reordering fixes rebuild speed immediately.
1.4. Use BuildKit Cache Mounts
BuildKit is the future, and AI knows its syntax well. Use this prompt to speed up dependency installation.
Prompt: "Refactor this Dockerfile to use BuildKit features: add
# syntax=docker/dockerfile:latest, useRUN --mount=type=cache,target=/root/.cache/pipfor pip, and--mount=type=bind,source=requirements.txt,target=/tmp/requirements.txtfor dependencies. Explain why cache mounts can be safely combined with layer caching."
This is a high-level prompt for teams already using modern Docker versions and looking for a CI speedup.
2. Docker Compose Prompts: Local Dev and Production Made Simple
A Dockerfile alone rarely runs a real application. You need compose to wire up the network, volumes, environment variables, and dependencies. Here are the prompts I use daily.
2.1. Full Dev Environment: Backend + PostgreSQL + Redis
This is the most common request I see on teams: one command to spin up a full stack.
Prompt: "Create a
docker-compose.ymlfor a FastAPI app in development mode. Services:api(build from current directory, mount source code as volume, hot reload with uvicorn, port 8000),postgres:16(volume for data, env vars, port 5432), andredis:7(port 6379). Add a named volume for Postgres and make the API wait for Postgres to be ready before starting. Version 4 of Compose."
Example outcome:
name: rocketapi-dev
services:
api:
build: .
command: uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
volumes:
- .:/app
ports:
- "8000:8000"
environment:
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/app
REDIS_URL: redis://redis:6379/0
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
postgres:
image: postgres:16
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 10
redis:
image: redis:7
ports:
- "6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
volumes:
pgdata:
Note how I explicitly asked for healthchecks and wait conditions. This avoids the classic connection refused error on the first docker compose up.
2.2. Compose for Production: Hardened Services
Production compose files need resource limits, restart policies, read-only root filesystems, and networks. AI can generate that if you ask explicitly.
Prompt: "Generate a production-grade
docker-compose.ymlfor the following services: [service list]. Use the deploy.resources.limits block for memory/cpu,restart: unless-stopped, non-root user in the Dockerfiles, and place all services on a custom network. Also add an internal network for database traffic only."
Adding the "internal network for database traffic only" forces the AI to think about network segmentation — a security level most beginner setups skip.
2.3. Profiles, Configs, and Secrets
AI can also modernize an existing Compose file. I regularly use this prompt:
Prompt: "Refactor this Compose file to use profiles for the dev, test, and prod stacks. Move secrets out of
environmentintosecretswith top-levelsecrets: secrets.yml. Show how to load config files withconfigs. Keep backward compatibility where possible."
This prompt is gold for teams preparing for a Kubernetes migration, since profiles and secrets map naturally to Kubernetes namespaces and ConfigMaps.
2.4. Database Migrations as a Compose Service
Migrations are a classic source of race conditions. Instead of running them manually, add a dedicated service.
Prompt: "Add a one-off migration service to my Docker Compose file. It should run
alembic upgrade headbefore the API starts. Useprofiles: [migrate]and document the command:docker compose --profile migrate run --rm migrate. Help me make the APIdepends_onthis service only when the profile is active."
This kind of prompt shows how AI can make operational workflows visible in code, rather than relying on tribal knowledge.
3. Image Size Optimization Prompts: Shave Off Megabytes
Every unnecessary megabyte in your Docker image slows down CI and increases cold-start time. These prompts helped me shrink 1.5 GB images to 150 MB.
3.1. Detect the Biggest Space Hogs
You can't optimize what you can't measure. The AI is great at interpreting docker history output.
Prompt: "Run this Docker image and help me reduce its size. Here is the output of
docker history myapp:latest: [paste output]. Identify which layers are largest, what's causing the bloat (via pacman, pip, npm leftovers), and suggest a concrete plan to shrink it by at least 60%. Also include the commands to verify the new size."
The AI will point out, for instance, that a RUN apt-get install layer left caches behind, and it will give you the exact rm -rf /var/lib/apt/lists/* fix.
3.2. Rewrite Using Distroless
Distroless images are a massive size win and a security win at the same time. The trick is keeping the runtime while dropping the shell.
Prompt: "Rewrite this Dockerfile to use gcr.io/distroless/base-debian12 as the final stage. Copy the compiled binary from a builder stage, use a non-root user, and explain how debugging changes when there is no shell in the image. Also state the new image size compared to the original."
It's perfect for Go, Rust, South, and Python applications when you want zero shell access in production.
3.3. The .dockerignore Audit
Sometimes you don't need to touch the Dockerfile at all — the build context is huge.
Prompt: "Generate an aggressive
.dockerignorefor a monorepo containing Node.js, Python, and Terraform directories. Exclude.git,node_modules,__pycache__,.terraform, logs, and test fixtures, but keep the directory structure needed for multi-stage builds. Explain the size difference with and without.dockerignore."
Lots of CI slowdowns are caused by the build context being shipped to the daemon. A good .dockerignore alone can slash build times by 80%.
3.4. Merge Layers and Squash Images
This prompt is for advanced users who want a final image with fewer layers, at the cost of losing cache granularity.
Prompt: "How can I squash my Docker image layers? Compare the
DOCKER_BUILDKITapproach, the experimental--squashflag, and leaving layers as-is. Which approach is safest for a production image that deploys to Kubernetes? Show before/afterdocker historyoutput."
It's a good educational prompt: it makes the AI explain the trade-offs instead of blindly applying an aggressive optimization.
4. Debugging Prompts: Diagnose Container Problems Fast
Time spent debugging an unknown container outage is the worst kind of time. These prompts turn an AI into a second pair of eyes that inspects logs, configs, and run output.
4.1. Container Exits Immediately
A classic problem with a dozen possible causes. Instead of Googling, let the AI generate a checklist and then read the results.
Prompt: "My container exits immediately. Here is my Dockerfile [paste it], the command I ran (
docker run --rm -it myapp), and thedocker logsoutput: [paste logs]. Give me a step-by-step diagnosis: entrypoint issues, signal handling, unmounted empty volume, or wrong working directory. Return the exact commands to test each hypothesis."
Frame the prompt as a diagnostic script, not a question: the AI will output concrete docker inspect, docker logs, and docker exec commands.
4.2. Container Is Running but Unreachable
One of the most frequent issues: the container runs, but localhost:8000 stays closed. Use this prompt:
Prompt: "My container runs but is not accessible from the host. Check my Compose file [paste it] and the output of
docker port myapp,docker network inspect, andcurl -v localhost:8000. Find the misconfigured port mapping, wrong bind interface (127.0.0.1 vs 0.0.0.0), or firewall issue. Give the fix and a verification command."
Here the AI acts as a network debugger, focusing on the exact discrepancy between mapped ports and app listening addresses.
4.3. High CPU or Memory in a Container
Resource spikes are hard to fix remotely. A good prompt will guide you toward strace, docker stats, and the right kernel limits.
Prompt: "My container eats 100% CPU after a few hours. Suggest a debugging sequence: how to use
docker stats,topinside the container, jstack for a Java app, and which kernel metrics to check (/sys/fs/cgroup/cpu, pids limit). Also propose a quick hotfix and a long-term fix."
It's a great prompt for production incidents because it pushes the AI to produce a triage workflow rather than an abstract answer.
4.4. DNS and Network Debugging Within Compose
Bad DNS inside containers is a whole category of pain:
Prompt: "My API service cannot resolve the hostname
postgreseven though the Compose service exists. Give me a checklist: container network inspect,getent hosts postgres, check if the container is actually on the same network, and how to fix it withnetworksexplicitly. Provide the exact commands."
The prompt forces the AI to remember one of the most common things developers forget: services must be on the same user-defined network to resolve each other by name.
5. Security Prompts: Harden Your Docker Setup
Security is not an afterthought — it's a requirement. These prompts generate Dockerfiles and Compose configs with security in mind.
5.1. Apply the CIS Docker Benchmark
The CIS benchmark is a standard for Docker hardening. Ask the AI to apply its rules to your file:
Prompt: "Review my Dockerfile and Compose file against the CIS Docker Benchmark. For each violation, state the rule number, severity, and the corrected version. Pay special attention to explicit USER,
--no-install-recommends, read-only root FS,cap_drop ALL, andno-new-privileges: true."
This is quite possibly the fastest way to get your images rated "production-ready" by an external security tool.
5.2. Vulnerability Scanning Instructions
Prompt the AI to create a scanning workflow:
Prompt: "Generate a shell script that scans my Docker images with Docker Scout and fails the build if any CVE has a severity of critical or high. Include output parsing for CI and a human-readable summary. Add a
docker scout quickviewcomparison against the base image."
You get both security and CI automation in one go.
5.3. Deny Root by Default
The simplest security win, and the most often missed. Use this prompt as a team rule:
Prompt: "Create a policy description for our team: why containers must never run as root (UID 0). Point to specific vulnerabilities (e.g., CVE-2019-5736, long-daemon attacks), how to create a non-root user in Alpine, Debian, and UBI base images, and what to do if the app requires binding to port 80."
It will also generate the correct USER and RUN chown lines for each base image.
6. Real-World Workflow Prompts: CI/CD and Automation
Docker doesn't stop at the developer machine. The following prompts take you from local images to fully automated CI/CD.
6.1. Build, Push, and Tag in GitHub Actions
Prompt: "Write a GitHub Actions workflow that builds a Docker image on every push to
main, tags it with the commit SHA and the wordlatest, scans it with Docker Scout, and pushes it to Docker Hub. Use cache from ghcr.io and keep the job under 5 minutes."
This converts the entire release pipeline into code that any team member can review.
6.2. Multi-Platform Images (AMD64 + ARM64)
Prompt: "Modify my build script to use
docker buildxwith--platform linux/amd64,linux/arm64and push a multi-arch manifest. Explain how to set up the builder properly withdocker buildx createand how to test the ARM64 image locally with QEMU."
Apple Silicon is everywhere now, and multi-arch is no longer optional.
6.3. Generate a Scaffold for a New Microservice
A powerful meta-prompt for teams building many services:
Prompt: "Act as a senior DevOps engineer. Scaffold a new microservice called
payment-servicewith: a Go 1.22 app skeleton, a Dockerfile with multi-stage build and distroless target, a Docker Compose service with healthcheck and resource limits, a.dockerignore, and aMakefilewithmake build,make run,make test. Keep everything in theservices/payment-servicedirectory. Output the full directory tree and each file content."
This single prompt can save 30–60 minutes per new service.
Quick Reference Table: AI Prompt Building Blocks
To make your own Docker prompts even better, combine these prompt segments like LEGO bricks:
| Category | What to ask for | Example segment |
|---|---|---|
| Base image | Runtime + version + official image | python:3.12-slim, node:20-alpine, golang:1.22 |
| Security | Non-root user, cap_drop, no-new-privileges | run as non-root, drop all capabilities |
| Performance | Layer cache, multi-stage, buildkit cache mounts | reorder COPY/RUN to maximize cache |
| Compose | Healthchecks, depends_on conditions, volumes | add healthcheck for postgres and redis |
| Debugging | Exact commands, logs, inspect output | give me step-by-step diagnostic commands |
| Output format | Code with explanation | return the optimized Dockerfile and explain each change |
Combine these with the actual constraints of your project, and the AI always knows what you expect.
Conclusion: Don't Memorize Docker, Automate It
Docker is not about memorizing every flag — it's about productive engineering. The prompts in this article give you a practical shortcut to the knowledge that normally takes years of trial and error. Start small: feed your current Dockerfile to an AI with the prompts from section 1.3 or 3.1, and watch the size and build time drop.
Here's my proposal for the next 7 days: choose three prompts, apply them to three real Dockerfiles in your project, and measure the difference. Most teams cut image sizes by more than 50% and remove hours of debugging time per month.
If you found value in this guide, bookmark it and share it with your team — the faster everyone around you writes clean Docker setup, the faster you ship. And if you're looking for more expert tips on containers, DevOps, and deployment workflows, explore the rest of the ASCII Blog: automation is a skill, and I document every trick I discover.
Happy containerizing!
Comments