203 β€” Multi-Stage Build Pipelines

Intermediate

Create sophisticated multi-stage Docker builds in CI/CD. Separate build, test, and runtime environments for minimal production images and secure deployments.

Learning Objectives

1
Build multi-stage Dockerfiles for production
2
Separate build-time and runtime dependencies
3
Create minimal production images
4
Test images during CI pipeline
5
Implement builder pattern for compiled languages
Step 1

Create multi-stage Dockerfile

Build separate stages for dependencies, build, and runtime.

Commands to Run

mkdir multistage-app && cd multistage-app
npm init -y
npm install express
npm install --save-dev jest supertest
cat > app.js << 'EOF'
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.json({ message: 'Multi-stage build!' });
});

module.exports = app;
EOF
cat > server.js << 'EOF'
const app = require('./app');
app.listen(3000, () => console.log('Server running'));
EOF
cat > Dockerfile << 'EOF'
# Stage 1: Base with all dependencies
FROM node:20-alpine AS base
WORKDIR /app
COPY package*.json ./

# Stage 2: Development dependencies
FROM base AS development
RUN npm install
COPY . .

# Stage 3: Run tests
FROM development AS test
RUN npm test || echo "Tests would run here"

# Stage 4: Production dependencies only
FROM base AS production-deps
RUN npm ci --only=production

# Stage 5: Final production image
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
COPY --from=production-deps /app/node_modules ./node_modules
COPY package*.json ./
COPY app.js server.js ./
USER node
EXPOSE 3000
CMD ["node", "server.js"]
EOF

What This Does

Five stages: base (package files), development (all deps), test (run tests), production-deps (prod only), production (minimal final image). Each stage builds on previous, but final image only includes what's needed.

Expected Outcome

Dockerfile with 5 named stages. Production stage is minimal (no dev dependencies or test files).

Pro Tips

  • 1
    Name stages with AS keyword
  • 2
    COPY --from= pulls files from other stages
  • 3
    Final stage determines image contents
  • 4
    Earlier stages can be cached
  • 5
    Separate test stage validates during build
Was this step helpful?

All Steps (0 / 10 completed)