Module 14 Lesson 1: Dockerizing a Node.js Full-Stack App
·DevOps

Module 14 Lesson 1: Dockerizing a Node.js Full-Stack App

From code to container. A step-by-step guide to containerizing a modern Node.js application with a React frontend, Express backend, and MongoDB database.

Module 14 Lesson 1: Project: Node.js Full-Stack App

In this project, we will apply everything we've learned to a MERN Stack (MongoDB, Express, React, Node) application.

1. The Architecture

  • Frontend: React (served via Nginx in production, Vite in dev).
  • Backend: Express.js API.
  • Database: MongoDB (official image).

2. The Backend Dockerfile (backend/Dockerfile)

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5000
CMD ["npm", "start"]

3. The Frontend Dockerfile (frontend/Dockerfile)

For production, we use a multi-stage build:

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

# Stage 2: Serve
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

4. The Orchestration (docker-compose.yml)

version: '3.8'

services:
  backend:
    build: ./backend
    ports:
      - "5000:5000"
    environment:
      - MONGO_URL=mongodb://db:2717/myapp
    depends_on:
      - db

  frontend:
    build: ./frontend
    ports:
      - "80:80"
    depends_on:
      - backend

  db:
    image: mongo:latest
    volumes:
      - mongo-data:/data/db

volumes:
  mongo-data:

5. Key Learning Points

  1. Networking: Notice how the backend uses mongodb://db to find the database. They share a default network.
  2. Persistence: The mongo-data volume ensures your user accounts and data aren't deleted when the container stops.
  3. Efficiency: The frontend uses Nginx, which is significantly faster and more secure at serving static HTML/JS than a Node.js server.

Exercise: The Deployment Challenge

  1. Clone a simple MERN starter kit from GitHub.
  2. Add the Dockerfiles and Compose file above.
  3. Run docker-compose up -d.
  4. Verify you can sign up a user in the UI and see the entry in the db container using docker exec.
  5. How would you change the backend to use Hot Reloading (Module 8) for development?
  6. Add a MAX_RETRY_TIMEOUT environment variable to the backend and verify it shows up inside the container.

Summary

You have just containerized a complete professional application. This setup is the foundation of modern web development and is exactly how apps are deployed to AWS, Heroku, and DigitalOcean every day.

Next Lesson: High Performance: Dockerizing a Python AI/ML workspace.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn