Dockerizing Applications and Production Builds - Textnotes

Dockerizing Applications and Production Builds


Learn how to containerize TypeScript applications using Docker and prepare production-ready builds. This module explains Docker setup, creating optimized images, and best practices for deploying TypeScript applications

1. Dockerizing TypeScript Applications

Docker allows running applications in isolated containers, ensuring consistent environments.

Dockerfile Example


# Use Node.js base image
FROM node:20-alpine

# Set working directory
WORKDIR /app

# Copy package files and install dependencies
COPY package*.json ./
RUN npm install

# Copy source code
COPY . .

# Build TypeScript code
RUN npm run build

# Expose port
EXPOSE 3000

# Start application
CMD ["node", "dist/index.js"]

Build and Run Docker Image


docker build -t my-ts-app .
docker run -p 3000:3000 my-ts-app

This ensures the TypeScript app runs consistently in any environment.

2. Production-Ready Builds

Optimizing TypeScript builds for production reduces image size and improves performance.

Strategies

  1. Compile TypeScript to JavaScript before building the image:

npx tsc --build
  1. Use multi-stage Docker builds to reduce final image size:

# Stage 1: Build
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Stage 2: Production
FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY package*.json ./
RUN npm install --production
EXPOSE 3000
CMD ["node", "dist/index.js"]
  1. Exclude development dependencies for a lighter image
  2. Minimize layers and cache dependencies for faster builds

Environment Variables

Use .env files and docker run --env-file to pass configuration safely:


docker run --env-file .env -p 3000:3000 my-ts-app

Conclusion

Dockerizing TypeScript applications ensures consistent runtime environments, scalable deployment, and simplified management. Multi-stage builds and production-ready optimizations reduce image size, enhance performance, and make deployment more reliable.