13. Docker Basics
What is Docker?
Docker packages your application and its environment (Node version, system libraries, environment variables) into a standardized unit called a container. Containers run identically on any machine.
The Problem Docker Solves
It works on my machine is the classic developer excuse. Your laptop has Node 18, but the server has Node 14. Your code crashes. Docker eliminates environment differences by including exactly the Node version your app needs inside the container.
# Without Docker: manual setup on every machine # Install Node 18 # Install MongoDB # Set environment variables # Run npm install # With Docker: one command docker compose up
What is a Dockerfile?
A Dockerfile is a text file with instructions for building a Docker image. Each instruction creates a layer. FROM sets the base image (like node:18-alpine). WORKDIR sets the working directory inside the container. COPY copies files from your computer into the container.
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . EXPOSE 3000 CMD ["node", "server.js"]
Building and Running Containers
First you build an image from a Dockerfile using docker build. Then you run a container from that image using docker run. Images are blueprints; containers are running instances.
# Build the image docker build -t my-node-app . # Run a container docker run -p 3000:3000 my-node-app # Run in background docker run -d -p 3000:3000 --name my-app my-node-app # View running containers docker ps # Stop a container docker stop my-app # View logs docker logs my-app
Docker Compose for Multi-Service Apps
Docker Compose defines and runs multiple containers together. One command starts your entire stack: API, database, cache, and more.
version: '3.8'
services:
api:
build: .
ports:
- "3000:3000"
environment:
- MONGODB_URI=mongodb://mongodb:27017/myapp
depends_on:
- mongodb
mongodb:
image: mongo:6
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
volumes:
mongodb_data:
# Start everything docker compose up -d # Stop everything docker compose down # View logs docker compose logs -f
Important Docker Commands
# List all images docker images # Remove an image docker rmi my-node-app # Execute a command inside a running container docker exec -it my-app sh # Copy files from container docker cp my-app:/app/logs ./logs # View resource usage docker stats
Knowledge Check
Ready to test your understanding of 13. Docker Basics?