JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstooling
PrevNext
tooling
senior
containerization

How do you containerize a JavaScript application with Docker?

docker
containerization
dockerfile
deployment
Quick Answer

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.

Detailed Explanation

Docker Concepts:

  • Dockerfile: Build instructions
  • Image: Built artifact
  • Container: Running instance
  • Multi-stage: Smaller final images

Best Practices:

  1. Use multi-stage builds
  2. Minimize layers
  3. Order for cache efficiency
  4. Use .dockerignore
  5. Run as non-root user
  6. Use specific Node versions

Optimization:

  • Copy package*.json first
  • Install deps before copying code
  • Use alpine images
  • Prune dev dependencies

Code Examples

Multi-stage Dockerfile
# 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"]

Resources

Docker Node.js Guide

docs

Docker Best Practices

docs

Related Questions

How do you set up CI/CD for a JavaScript project?

mid
ci-cd
Previous
How does Babel work and how do you configure it?
Next
How do you optimize build times for large JavaScript projects?