Container
Container
A technology that packages an application and its dependencies in an isolated environment. Docker is the de facto standard, and containers are lighter than VMs and start faster.
Container
A technology that packages an application and its dependencies in an isolated environment. Docker is the de facto standard, and containers are lighter than VMs and start faster.
A container is a technology that bundles an application and its dependencies (libraries, configuration files, runtime environment) into a single package and runs it in an isolated environment. It became popular with the emergence of Docker in 2013 and is a core foundational technology of modern cloud-native architecture.
Technical principles: Containers use the Linux kernel's namespaces (isolation of processes, network, and file system) and cgroups (limits on CPU and memory resources). Unlike a virtual machine (VM), which virtualizes an entire guest OS on top of a hypervisor, a container shares the host OS kernel and is therefore much lighter. Start-up time is measured in seconds, and image sizes are small, at tens to hundreds of MB.
| Item | Virtual Machine (VM) | Container |
|---|---|---|
| Start-up Time | Minutes | Seconds (milliseconds are also possible) |
| Image Size | Several GB to tens of GB | Tens of MB to hundreds of MB |
| Isolation Level | Strong (hardware level) | Weak (process level) |
| Resource overhead | High (entire guest OS) | Low (application only) |
Image layers: A container image consists of a stack of read-only layers. Each instruction in a Dockerfile (RUN, COPY, etc.) creates a new layer, and containers that use the same base image share layers, saving disk space. When a container runs, a writable layer is added on top.
OCI standard: Docker was the de facto standard, but today there are various runtimes, such as containerd, CRI-O, and Podman, based on the OCI (Open Container Initiative) standard. Kubernetes supports multiple runtimes through the CRI (Container Runtime Interface).
# === Dockerfile (Node.js 앱 예제) ===
# 1. 베이스 이미지 선택 (alpine = 경량 Linux)
FROM node:20-alpine
# 2. 작업 디렉토리 설정
WORKDIR /app
# 3. 의존성 파일만 먼저 복사 (캐시 최적화)
COPY package*.json ./
# 4. 의존성 설치
RUN npm ci --only=production
# 5. 애플리케이션 코드 복사
COPY . .
# 6. 비루트 사용자로 전환 (보안)
RUN addgroup -g 1001 -S nodejs \
&& adduser -S nodejs -u 1001
USER nodejs
# 7. 환경 변수 설정
ENV NODE_ENV=production
ENV PORT=3000
# 8. 포트 노출 (문서화 목적)
EXPOSE 3000
# 9. 헬스체크 설정
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
# 10. 컨테이너 시작 명령
CMD ["node", "server.js"]
# === 멀티스테이지 빌드 (빌드 도구 제외로 이미지 경량화) ===
# ========== Stage 1: 빌드 ==========
FROM node:20-alpine AS builder
WORKDIR /app
# 의존성 설치 (devDependencies 포함)
COPY package*.json ./
RUN npm ci
# TypeScript 빌드
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
# 빌드 결과물과 프로덕션 의존성만 복사
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
EXPOSE 3000
CMD ["node", "dist/server.js"]
# 결과: 빌드 스테이지의 TypeScript, 소스코드, devDependencies 제외
# 이미지 크기: 약 1GB → 약 150MB로 감소
# === docker-compose.yml (로컬 개발 환경) ===
version: "3.9"
services:
# 애플리케이션
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
environment:
- NODE_ENV=development
- DATABASE_URL=postgres://user:pass@db:5432/myapp
- REDIS_URL=redis://redis:6379
volumes:
- .:/app # 소스 코드 바인드 마운트
- /app/node_modules # node_modules는 컨테이너 것 사용
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
networks:
- app-network
# PostgreSQL 데이터베이스
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: myapp
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
interval: 10s
timeout: 5s
retries: 5
networks:
- app-network
# Redis 캐시
redis:
image: redis:7-alpine
command: redis-server --appendonly yes
volumes:
- redis_data:/data
networks:
- app-network
# Nginx 리버스 프록시
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- app
networks:
- app-network
volumes:
postgres_data:
redis_data:
networks:
app-network:
driver: bridge
# === Docker 기본 명령어 ===
# 이미지 빌드
docker build -t myapp:v1.0 .
docker build -f Dockerfile.prod -t myapp:prod .
# 컨테이너 실행
docker run -d --name myapp -p 3000:3000 myapp:v1.0
docker run -it --rm myapp:v1.0 /bin/sh # 대화형 쉘
# 컨테이너 관리
docker ps # 실행 중인 컨테이너
docker ps -a # 모든 컨테이너
docker logs -f myapp # 로그 실시간 확인
docker exec -it myapp /bin/sh # 실행 중 컨테이너 접속
docker stop myapp && docker rm myapp # 정지 및 삭제
# 이미지 관리
docker images # 이미지 목록
docker rmi myapp:v1.0 # 이미지 삭제
docker image prune -a # 미사용 이미지 정리
# === Docker Compose 명령어 ===
docker compose up -d # 백그라운드 실행
docker compose up --build # 이미지 재빌드 후 실행
docker compose logs -f app # 특정 서비스 로그
docker compose exec app sh # 컨테이너 접속
docker compose down # 정지 및 컨테이너 삭제
docker compose down -v # 볼륨까지 삭제
# === 이미지 레지스트리 ===
docker login # Docker Hub 로그인
docker tag myapp:v1.0 username/myapp:v1.0 # 태깅
docker push username/myapp:v1.0 # 푸시
docker pull username/myapp:v1.0 # 풀
# === 보안 스캔 ===
docker scout cves myapp:v1.0 # Docker Scout 취약점 스캔
trivy image myapp:v1.0 # Trivy로 스캔
"The 'it works locally but not on the server' issue has come up again. Let's standardize the development environment with Docker too. With a single docker-compose up, everything from the DB and Redis to the app will come up. Onboarding for new hires will also be much faster."
"The Dockerfile image size is 1.2GB. If we switch to an Alpine base and exclude the build tools with a multi-stage build, we can bring it down to under 150MB. Also, it is running as root, so please add a non-root user using the USER directive."
"The differences between containers and virtual machines are the isolation level and resource efficiency. A VM virtualizes an entire guest OS on top of a hypervisor, whereas a container shares the host kernel and isolates at the process level using namespaces and cgroups. Containers start quickly and are lightweight, but because they share the kernel, their isolation is weaker than that of VMs. In security-critical multi-tenant environments, consider VMs or microVMs such as Firecracker."
"The container keeps restarting with OOMKilled. I checked with docker stats, and it keeps hitting the memory limit. If it's Node.js, I think we should set the heap size to about 75% of the container limit with the --max-old-space-size option, and check whether there is a memory leak."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If you run a container as root, the entire host system is put at risk when a container escape vulnerability occurs. Be sure to set a non-root user (USER directive). Also, never use the --privileged flag.
Containers are ephemeral. When a container is deleted, the data inside it is also lost. Be sure to store persistent data such as DB data, logs, and uploaded files using volumes (-v or volumes) or in external storage (S3, etc.).
Arbitrary images on Docker Hub may contain malware or vulnerabilities. Use only official images or images from verified publishers, and scan for vulnerabilities with Trivy or Docker Scout.
Build tools (TypeScript, Webpack, etc.) and devDependencies are not needed at runtime. Separating the build stage from the runtime stage with a multi-stage build can reduce the image size by more than 80%.