
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
- Networking: Notice how the backend uses
mongodb://dbto find the database. They share a default network. - Persistence: The
mongo-datavolume ensures your user accounts and data aren't deleted when the container stops. - 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
- Clone a simple MERN starter kit from GitHub.
- Add the Dockerfiles and Compose file above.
- Run
docker-compose up -d. - Verify you can sign up a user in the UI and see the entry in the
dbcontainer usingdocker exec. - How would you change the
backendto use Hot Reloading (Module 8) for development? - Add a
MAX_RETRY_TIMEOUTenvironment 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.