Docker
Docker
A container-based virtualization platform. Packages applications as images so they run identically anywhere. The de facto standard for standardizing development environments.
Docker
A container-based virtualization platform. Packages applications as images so they run identically anywhere. The de facto standard for standardizing development environments.
Docker is a container platform released in 2013 by Docker Inc. (formerly dotCloud). Under the "Build, Ship, Run" philosophy, it solved the problem of inconsistent development environments ("It works on my machine..."). It made Linux Containers (LXC) technology user-friendly and popularized it, and it is currently used by more than 15 million developers worldwide.
Docker Ecosystem:
Container runtime. Consists of the dockerd daemon, containerd, and runc
GUI app for Mac/Windows. Runs Linux containers on top of a VM
Public image registry. Provides Official images and community images
Multi-container definition. Declares services, networks, and volumes in YAML
Core Concepts: Docker works through the relationship between images (Image) and containers (Container). An image is a read-only template (class), and a container is a running instance (object) of an image. You define an image with a Dockerfile, build it with docker build, and run a container with docker run.
License Change: Since 2021, Docker Desktop has been paid for large enterprises (250 or more employees or annual revenue of $10M or more). Open-source alternatives include Podman (Red Hat), Rancher Desktop, and Colima (macOS), and thanks to OCI standard compatibility they can be used almost identically to Docker commands.
# === Docker 기본 명령어 ===
# 이미지 관리
docker pull node:20-alpine # 이미지 다운로드
docker images # 로컬 이미지 목록
docker rmi node:20-alpine # 이미지 삭제
docker image prune -a # 미사용 이미지 전체 삭제
# 컨테이너 실행
docker run -d --name myapp -p 3000:3000 myapp:v1
# -d: 백그라운드 실행 (detached)
# --name: 컨테이너 이름 지정
# -p: 포트 매핑 (호스트:컨테이너)
docker run -it --rm node:20-alpine /bin/sh
# -it: 대화형 터미널
# --rm: 종료 시 자동 삭제
# 환경 변수 & 볼륨
docker run -d \
-e NODE_ENV=production \
-e DATABASE_URL=postgres://... \
-v $(pwd)/data:/app/data \
-v /app/node_modules \
myapp:v1
# 컨테이너 관리
docker ps # 실행 중인 컨테이너
docker ps -a # 모든 컨테이너 (정지 포함)
docker logs -f myapp # 로그 실시간 확인
docker exec -it myapp /bin/sh # 실행 중 컨테이너 접속
docker stop myapp # 컨테이너 정지
docker rm myapp # 컨테이너 삭제
docker container prune # 정지된 컨테이너 전체 삭제
# 이미지 빌드 & 푸시
docker build -t username/myapp:v1 .
docker login # Docker Hub 로그인
docker push username/myapp:v1 # 이미지 업로드
# 시스템 정리
docker system df # 디스크 사용량 확인
docker system prune -a --volumes # 미사용 리소스 전체 정리 (주의!)
# 네트워크
docker network create app-network # 사용자 정의 네트워크 생성
docker network ls # 네트워크 목록
docker run -d --network app-network --name db postgres:16
# === Dockerfile 베스트 프랙티스 ===
# 1. 멀티스테이지 빌드 (이미지 경량화)
# ===== Stage 1: 빌드 =====
FROM node:20-alpine AS builder
WORKDIR /app
# 의존성 파일만 먼저 복사 (캐시 최적화)
COPY package*.json ./
RUN npm ci
# 소스 코드 복사 & 빌드
COPY tsconfig.json ./
COPY src/ ./src/
RUN npm run build
# 프로덕션 의존성만 재설치
RUN npm ci --only=production && npm cache clean --force
# ===== Stage 2: 런타임 =====
FROM node:20-alpine AS runner
# 보안: 비루트 사용자 설정
RUN addgroup -g 1001 -S nodejs \
&& adduser -S nodejs -u 1001
WORKDIR /app
# 빌드 결과물만 복사 (소스코드, devDeps 제외)
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nodejs:nodejs /app/package.json ./
# 비루트 사용자로 전환
USER nodejs
# 환경 변수 설정
ENV NODE_ENV=production
ENV PORT=3000
# 포트 노출 (문서화 목적)
EXPOSE 3000
# 헬스체크
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
# 실행 명령
CMD ["node", "dist/server.js"]
# === 결과 ===
# 빌드 스테이지: ~1GB (node_modules, TypeScript, 소스코드)
# 런타임 스테이지: ~150MB (Alpine + dist + production deps만)
# === docker-compose.yml (로컬 개발 환경) ===
version: "3.9"
services:
# Node.js 애플리케이션
app:
build:
context: .
dockerfile: Dockerfile.dev
container_name: myapp
ports:
- "3000:3000"
- "9229:9229" # 디버깅 포트
environment:
- NODE_ENV=development
- DATABASE_URL=postgres://user:password@db:5432/myapp
- REDIS_URL=redis://redis:6379
volumes:
- .:/app # 소스코드 바인드 마운트 (핫 리로드)
- /app/node_modules # node_modules는 컨테이너 것 사용
depends_on:
db:
condition: service_healthy
networks:
- app-network
command: npm run dev # 개발 서버 실행
# PostgreSQL 데이터베이스
db:
image: postgres:16-alpine
container_name: myapp-db
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
interval: 5s
timeout: 5s
retries: 5
networks:
- app-network
# Redis 캐시
redis:
image: redis:7-alpine
container_name: myapp-redis
command: redis-server --appendonly yes
volumes:
- redis_data:/data
networks:
- app-network
# Named Volumes (데이터 영속화)
volumes:
postgres_data:
redis_data:
# 네트워크
networks:
app-network:
driver: bridge
# === 명령어 ===
# docker compose up -d # 백그라운드 실행
# docker compose up --build # 이미지 재빌드 후 실행
# docker compose logs -f app # app 서비스 로그 확인
# docker compose exec app sh # app 컨테이너 접속
# docker compose down # 정지 및 삭제
# docker compose down -v # 볼륨까지 삭제
"With just one line of docker compose up in the README, the entire development environment comes up. The DB, Redis, and the app too. You don't need to match the Node version or install PostgreSQL. You can start writing code from day one."
"The reason for COPYing only package.json first, before npm install, in the Dockerfile is cache optimization. If only the source code changes, the dependency installation layer is pulled from the cache, so the build time drops from 3 minutes to 30 seconds."
"I have experience optimizing Docker image size. I switched to an Alpine base, excluded build tools with a multi-stage build, and excluded unnecessary files with .dockerignore, cutting it by 90% from 1.2GB to 120MB. Both CI/CD time and registry costs improved."
"We scan images for vulnerabilities with Docker Scout or Trivy. When a base image CVE is found, Renovate Bot automatically opens a PR, and a deployment only goes through if it passes the scan in CI. Pinning versions instead of using the latest tag is also important."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
The default is root. If a container escape vulnerability occurs, the entire host is put at risk. Set a non-root user with the USER directive in the Dockerfile. Never use the --privileged flag.
FROM node:latest can change versions at any time, so builds are not reproducible. Always specify a version: node:20.11.1-alpine. Otherwise it can cause builds to suddenly break in CI.
Docker Desktop is paid for large enterprises (250+ employees or $10M+ revenue). Consider free alternatives such as Podman, Colima, and Rancher Desktop. The CLI is still free.
Add node_modules, .git, .env, test files, and so on to .dockerignore. This shrinks the build context, which speeds up builds, and prevents sensitive information from being included in the image.