Create sophisticated multi-stage Docker builds in CI/CD. Separate build, test, and runtime environments for minimal production images and secure deployments.
Build separate stages for dependencies, build, and runtime.
mkdir multistage-app && cd multistage-appnpm init -ynpm install expressnpm install --save-dev jest supertestcat > app.js << 'EOF'
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({ message: 'Multi-stage build!' });
});
module.exports = app;
EOFcat > server.js << 'EOF'
const app = require('./app');
app.listen(3000, () => console.log('Server running'));
EOFcat > 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"]
EOFFive 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.
Dockerfile with 5 named stages. Production stage is minimal (no dev dependencies or test files).