Build a secure multi-stage Dockerfile for web apps

Produce a production-grade, secure, multi-stage Dockerfile tailored to your runtime. Use it when containerizing a web backend or frontend application.

Prompt

Prompt
Act as a DevOps and container security engineer. You will create an optimized, secure multi-stage Dockerfile and matching .dockerignore file for my application.

First, ask me 3 short numbered questions in one message and wait for my response:
1. What is your programming language and framework runtime (e.g., Node 20, Python 3.12, Go 1.22)?
2. What package manager and build command does your app require (e.g., npm run build, poetry, cargo)?
3. Does the app serve static assets, run as a long-lived web server, or need specific OS libraries?

After I answer, output:
1. Dockerfile (fenced code block with multi-stage build, layer caching, non-root user, and dumb-init/tini where appropriate)
2. .dockerignore file (fenced code block)
3. Build and run commands (terminal snippet)
4. Security & size checklist (short bullet points)

Example output

Example for: Node.js 20 Express API using pnpm

1. Dockerfile
# Stage 1: Dependencies and Build
FROM node:20-alpine AS builder
WORKDIR /app
RUN corepack enable && corepack prepare pnpm@latest --activate
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm run build

# Stage 2: Production Runner
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN apk add --no-cache dumb-init
RUN addgroup -g 1001 -S nodejs && adduser -S appuser -u 1001 -G nodejs

COPY --from=builder --chown=appuser:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:nodejs /app/dist ./dist
COPY --from=builder --chown=appuser:nodejs /app/package.json ./package.json

USER appuser
EXPOSE 3000
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "dist/index.js"]
2. .dockerignore
node_modules
.git
.env*
dist
*.md
.DS_Store
3. Build and Run Commands
docker build -t web-app:latest .
docker run -p 3000:3000 -d --name my-web-app web-app:latest
4. Security & Size Checklist
  • Uses minimal Alpine base image to reduce attack surface and build size.
  • Drops privileges to non-root appuser before listening on the port.
  • Leverages dumb-init to handle PID 1 signal forwarding properly.
Written by AI from this prompt. Your results will vary.

Copy and paste this prompt into Gemini, ChatGPT, or Claude. Answer the three questions the model asks, then ask for a docker-compose.yml file as a follow-up.

Make it repeatable

Keep using this prompt without pasting it in every time.

Keep exploring

More in Coding