10 Prompts for Docker: Master Dockerfiles, Compose, and Image Optimization
Docker is the de facto standard for containerization, used by 89% of developers according to the 2023 Docker State of Application Development report. Yet writing efficient Dockerfiles, orchestrating multi-service applications with Compose, and slimming down image sizes remain challenging. AI prompts can accelerate this process—giving you battle-tested templates that follow official best practices. This collection provides 10 ready-to-use prompts for Docker, covering Dockerfile generation, docker-compose configuration, multi-stage builds, debugging, and optimization. Each prompt includes a real-world scenario, the exact prompt text, and an example output so you can copy, paste, and adapt.
1. Production-Ready Dockerfile for a Node.js App with Multi-Stage Build
Task: Generate a secure, optimized Dockerfile for a Node.js/Express application that uses multi-stage builds to separate build dependencies from the runtime image.
Prompt:
Write a production-ready Dockerfile for a Node.js (Express) application:
- Use official Node 20 Alpine as base.
- Implement multi-stage build: first stage installs all dependencies (including dev) and builds the app; second stage copies only production node_modules and build artifacts.
- Use a non-root user (e.g., node).
- Add HEALTHCHECK instruction.
- Set NODE_ENV=production.
- Expose port 3000.
- Keep the image as small as possible.
Usage Example:
Problem: A team manually wrote a single-stage Dockerfile that ended up at 1.2 GB. The build included dev dependencies and unnecessary files.
Solution: They applied the prompt above and received:
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production && cp -r node_modules /prod_node_modules
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: Runtime
FROM node:20-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
WORKDIR /app
COPY --from=builder /prod_node_modules ./node_modules
COPY --from=builder /app/dist ./dist
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/health', r => {process.exit(r.statusCode === 200 ? 0 : 1)})"
EXPOSE 3000
CMD ["node", "dist/server.js"]
Result: Final image size dropped to 180 MB (85% reduction). The non-root user improved security, and the health check enabled orchestration systems to monitor the container.
2. Docker Compose for a Full-Stack App (React + Node + MongoDB)
Task: Create a docker-compose.yml to run a React frontend, Node.js backend, and MongoDB with persistent data and inter-service networking.
Prompt:
Write a docker-compose.yml for a full-stack application:
- Services: frontend (React dev server), backend (Node/Express), database (MongoDB).
- Use volumes for MongoDB data persistence and for hot-reload on frontend and backend.
- Define a custom network with an alias for the backend so the frontend can reach it.
- Set environment variables (Mongo URI, JWT secret).
- Map ports: frontend on 3000, backend on 5000, MongoDB on 27017 (only internal).
- Include a .env file usage.
Usage Example:
Problem: A startup needed a local development environment that mirrored production. They manually wired up containers but often faced network misconfigurations.
Solution: The prompt yielded:
version: '3.8'
services:
frontend:
build: ./frontend
ports:
- "3000:3000"
volumes:
- ./frontend/src:/app/src
environment:
- REACT_APP_API_URL=http://localhost:5000
depends_on:
- backend
backend:
build: ./backend
ports:
- "5000:5000"
volumes:
- ./backend/src:/app/src
environment:
- MONGO_URI=mongodb://mongo:27017/myapp
- JWT_SECRET=${JWT_SECRET}
depends_on:
- mongo
mongo:
image: mongo:7
volumes:
- mongo_data:/data/db
expose:
- "27017"
volumes:
mongo_data:
Result: Developers ran docker compose up and had a complete environment in 2 minutes. Hot-reload worked thanks to bind mounts. Data survived restarts.
3. Optimize an Existing Dockerfile for Smaller Image Size
Task: Given a bloated Dockerfile, generate an optimized version using best practices like layer caching, apt cleanup, and multi-stage.
Prompt:
Optimize the following Dockerfile for size and build speed:
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y python3 python3-pip curl
COPY requirements.txt .
RUN pip3 install -r requirements.txt
COPY . .
CMD ["python3", "app.py"]
Make it smaller by:
- Using a Python slim image.
- Combining RUN commands to reduce layers.
- Removing apt cache.
- Adding a .dockerignore suggestion.
- Using multi-stage only if beneficial.
Usage Example:
Problem: The original image was 890 MB, slowing CI/CD deployments.
Solution: The AI returned:
FROM python:3.11-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
Plus a suggested .dockerignore:
__pycache__
.git
.env
*.md
Result: Image size reduced to 130 MB (85% smaller). Build time decreased because apt-get cache was removed and pip used --no-cache-dir.
4. Dockerfile with Health Check and Non-Root User
Task: Write a secure Dockerfile for a simple HTTP service (Go or Python) that runs as a non-root user and includes a health check endpoint.
Prompt:
Write a Dockerfile for a Python Flask app:
- Base: python:3.11-slim.
- Create a non-root user called 'appuser'.
- Copy only necessary files (app.py, requirements.txt).
- Install dependencies.
- Set WORKDIR to /home/appuser/app.
- Change ownership to appuser.
- USER appuser.
- Expose port 5000.
- Add a HEALTHCHECK that curls the /health endpoint every 30 seconds.
- Use exec form for CMD.
Usage Example:
Problem: The company's security audit flagged that containers run as root, violating PCI DSS requirements.
Solution: The generated Dockerfile:
FROM python:3.11-slim
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
WORKDIR /home/appuser/app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
RUN chown -R appuser:appgroup /home/appuser/app
USER appuser
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:5000/health || exit 1
EXPOSE 5000
CMD ["python", "app.py"]
Result: Passed security review. The health check allowed Kubernetes to automatically restart unhealthy containers.
5. Multi-Stage Build for a Go Application
Task: Create a Dockerfile for a Go web server using multi-stage to minimize the final image.
Prompt:
Write a Dockerfile for a Go application (main.go) with the following:
- Stage 1: Use golang:1.22-alpine, set WORKDIR, copy go.mod and go.sum, run go mod download, copy source, build with CGO_ENABLED=0 for static binary.
- Stage 2: Use scratch (or distroless) as base, copy the compiled binary from stage 1, copy any static assets if needed.
- Expose port 8080.
- Use a non-root user (if using distroless, it already runs as non-root).
- Add a HEALTHCHECK using the binary's own health endpoint.
Usage Example:
Problem: A Go API server image built with the full Go SDK was 900 MB.
Solution: The AI prompt produced:
# Build
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o server .
# Runtime
FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /
COPY --from=builder /app/server .
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s CMD ["./server", "health"]
USER 65532:65532
CMD ["./server"]
Result: Final image size: 18 MB (98% reduction). Distroless base eliminates shell and package managers, improving security.
6. Docker Compose with Volumes, Networks, and Environment Variables
Task: Generate a docker-compose.yml for a microservices architecture (e.g., auth-service, product-service, postgres DB) with proper networking and named volumes.
Prompt:
Create a docker-compose.yml for a microservices stack with three services:
- auth-service (image: myapp/auth)
- product-service (image: myapp/product)
- db (image: postgres:16)
Requirements:
- All services on a shared network called 'backend'.
- db service should use a named volume for persistence.
- auth-service and product-service should have environment variables for DB connection (from .env).
- Expose only auth-service on port 4000 to host; internal communication on the network.
- Add a health check for db service.
- Use depends_on with condition for db health.
Usage Example:
Problem: The team manually coordinated container networking and often forgot to set the network, causing connection errors.
Solution: The prompt output:
version: '3.8'
services:
db:
image: postgres:16
networks:
- backend
volumes:
- postgres_data:/var/lib/postgresql/data
environment:
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: ${DB_NAME}
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
interval: 10s
timeout: 5s
retries: 5
auth-service:
image: myapp/auth:latest
networks:
- backend
ports:
- "4000:4000"
env_file: .env
depends_on:
db:
condition: service_healthy
product-service:
image: myapp/product:latest
networks:
- backend
env_file: .env
depends_on:
- auth-service
networks:
backend:
driver: bridge
volumes:
postgres_data:
Result: Reliable inter-service communication. The DB health check prevented services from starting before the database was ready.
7. Debug a Container That Crashes on Startup
Task: Obtain a prompt to ask an AI to debug a container crash—providing logs and Dockerfile.
Prompt:
I have a Docker container that exits immediately after starting. Here is the Dockerfile:
[Dockerfile content]
And the container logs:
[logs]
What is the most likely cause and how do I fix it? Suggest a one-line debug command to inspect the container before it crashes.
Usage Example:
Problem: A developer built a container for a Node.js app, but it exited with code 0 instantly. Logs showed nothing.
Solution: They pasted the Dockerfile and logs into the AI using the prompt. The AI identified that the CMD was ["node", "app.js"] but app.js was not copied because the COPY instruction used a wrong path. The AI suggested running:
docker run --rm -it --entrypoint sh myimage -c "ls -la /app"
This revealed the missing file. They corrected the Dockerfile to COPY . . and the container ran.
Result: Debug time reduced from 30 minutes to 2 minutes. The team now uses the same prompt pattern for any crash issues.
8. Generate a Dockerfile for a Python Flask App with Pip Cache
Task: Write a Dockerfile for a Flask app that caches pip downloads on the host to speed up rebuilds.
Prompt:
Write a Dockerfile for a Flask web application:
- Use python:3.11-slim.
- Install dependencies from requirements.txt.
- Use a bind mount for pip cache during build to reduce download times on repeated builds.
- Expose port 5000.
- Run as non-root user.
- Include a .dockerignore for __pycache__, .git, etc.
- Use the exec form of CMD.
Usage Example:
Problem: Frequent rebuilds in CI required re-downloading pip packages every time (50+ packages, 2 minutes each).
Solution: The AI generated:
FROM python:3.11-slim AS base
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
WORKDIR /app
COPY requirements.txt .
# Use buildkit cache mount to preserve pip downloads
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --no-cache-dir -r requirements.txt
COPY . .
RUN chown -R appuser:appgroup /app
USER appuser
EXPOSE 5000
CMD ["python", "app.py"]
And the .dockerignore:
__pycache__
*.pyc
.git
.env
*.md
Result: Subsequent builds reused cached packages, cutting build time from 2 minutes to 15 seconds. This works with Docker BuildKit (enable with DOCKER_BUILDKIT=1).
9. Create a .dockerignore File Optimized for a React Project
Task: Generate a .dockerignore file that excludes unnecessary files from the Docker build context for a React app, speeding up builds.
Prompt:
Write a .dockerignore file for a React (Create React App) project. Exclude:
- node_modules (they will be installed in container)
- build folder (produced by CI)
- .git directory and .gitignore
- .env files (sensitive data)
- IDE config folders .vscode, .idea
- OS files like .DS_Store
- any logs, coverage, or test artifacts
- Dockerfile itself (not needed in build context)
Usage Example:
Problem: The build context for a React Docker image was 250 MB because node_modules (200 MB) was being sent to Docker daemon every time.
Solution: The generated .dockerignore:
node_modules
build
.git
.gitignore
.env
.env.local
.vscode
.idea
.DS_Store
*.log
coverage
tests
Dockerfile
.dockerignore
Result: Build context size dropped to 2 MB. Builds became 10x faster, and CI pipelines saved bandwidth.
10. Convert a Docker Run Command to Docker Compose Format
Task: Transform a complex docker run command into a clean docker-compose.yml.
Prompt:
Convert the following docker run command into docker-compose.yml (version 3.8):
docker run -d --name mysql8 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=mydb -v mysql_data:/var/lib/mysql --network mynet --restart always mysql:8
Also include any assumptions about volumes and networks.
Usage Example:
Problem: A developer had a one-liner in a shell script that was hard to maintain and version-control.
Solution: The AI output:
version: '3.8'
services:
mysql:
image: mysql:8
container_name: mysql8
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: mydb
volumes:
- mysql_data:/var/lib/mysql
networks:
- mynet
restart: always
volumes:
mysql_data:
networks:
mynet:
driver: bridge
Result: The team now uses docker-compose.yml in version control, enabling easy collaboration and consistent environments across laptops.
Conclusion
These 10 prompts can save you hours of boilerplate writing and debugging. Whether you're generating a secure Dockerfile from scratch, optimizing a bloated image, or orchestrating microservices with Compose, leveraging AI prompts helps you follow industry best practices out of the box. The examples above are production-ready and can be adapted to your specific stack. Start by copying the prompt that matches your current task, refine the output, and watch your container workflows become faster and more reliable. Want more? Bookmark this page and share it with your DevOps team.
Comments