Learn the concept
Docker for JavaScript Applications
Create a Dockerfile with multi-stage builds: first stage installs dependencies and builds, second stage copies only production files for smaller images. Use .dockerignore, optimize layer caching, and consider Node.js-specific best practices like running as non-root.
Docker Concepts:
Best Practices:
Optimization:
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files first (cache layer)
COPY package*.json ./
# Install ALL dependencies (including dev)
RUN npm ci
# Copy source and build
COPY . .
RUN npm run build
# Prune dev dependencies
RUN npm prune --production
# Stage 2: Production
FROM node:20-alpine AS production
WORKDIR /app
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
# Copy built files and production deps
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
# Set ownership
RUN chown -R nodejs:nodejs /app
USER nodejs
# Environment
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]Creating a multi-stage Dockerfile for the Node.js application, optimizing for small image size and security by using a non-root user and minimal base image (e.g., Alpine). The Docker image then becomes the deployable unit in Kubernetes.
Using Docker Compose to define and run multi-container Docker applications. This ensures that all services are consistently configured and easily brought up or down, mirroring production environments.
Containerizing the build process itself by running `npm install` and `npm run build` inside a Docker container. This locks down dependencies and system tools, preventing 'works on my machine' issues in CI/CD pipelines.
Create a basic Express.js API. Write a multi-stage Dockerfile to containerize it, expose a port, and ensure it runs as a non-root user. Use Docker Compose to run the API with a PostgreSQL database.
Set up a React application with a `Dockerfile` that builds the frontend assets. Configure a `nginx` Docker container to serve these static assets, demonstrating a production-ready containerized setup.
Netflix heavily utilizes Docker and Kubernetes for deploying and managing its vast microservices architecture. Docker provides consistent environments for their services, from development to production, enabling rapid deployment and scaling.
Spotify uses Docker extensively for its backend services, ensuring portability and scalability across different environments. Their use of Docker helps standardize their development workflows and simplifies the management of their diverse technology stack.