Docker
Beginner
1 min read
Targeting Build Stages with --target
Example
# Dockerfile with dev, test, and production targets
FROM node:20-alpine AS base
WORKDIR /app
COPY package.json package-lock.json ./
# dev stage (includes all deps + hot reload)
FROM base AS dev
RUN npm install
COPY . .
ENV NODE_ENV=development
CMD ["node","--watch","src/server.js"]
# test stage (run test suite at build time)
FROM dev AS test
RUN npm test
# production deps
FROM base AS prod-deps
RUN npm ci --omit=dev
# production stage
FROM node:20-alpine AS production
WORKDIR /app
COPY --from=prod-deps /app/node_modules ./node_modules
COPY src/ ./src/
ENV NODE_ENV=production PORT=3000
EXPOSE 3000
CMD ["node","src/server.js"]
# Build dev image
# docker build --target dev -t myapp:dev .
# Run tests (build fails if tests fail)
# docker build --target test -t myapp:test .
# Build production image
# docker build --target production -t myapp:prod .
Related Resources
Docker Reference
Complete tag & property list
Docker How-To Guides
Step-by-step practical guides
Docker Exercises
Practice what you've learned
More in Docker