시작하기
기본 커맨드
docker run은 컨테이너를 만들고 시작합니다. -d는 백그라운드 실행, -p는 호스트 포트-컨테이너 포트 매핑입니다. pull은 레지스트리에서 이미지를 내려받습니다(기본값 Docker Hub).
# check version
docker --version
# pull an image
docker pull nginx:latest
# run a container
docker run -d --name mynginx -p 8080:80 nginx
# list running containers
docker ps
# list all containers (including stopped)
docker ps -a
# stop and remove a container
docker stop mynginx
docker rm mynginx
# list images
docker images컨테이너 라이프사이클
create + start가 run이 내부적으로 하는 일입니다. stop은 정상 종료를 위해 SIGTERM을 보내고, kill은 즉시 SIGKILL을 보냅니다. pause는 cgroup freezer를 사용합니다 — 프로세스를 멈추지 않고 스냅샷을 찍을 때 유용합니다.
# create a container without starting it
docker create --name web nginx
# start a created (or stopped) container
docker start web
# stop gracefully (SIGTERM then SIGKILL after 10s)
docker stop web
# force kill immediately
docker kill web
# restart a container
docker restart web
# pause/resume (freezes process with cgroups)
docker pause web
docker unpause web이미지 기본
이미지는 읽기 전용 레이어들입니다. 컨테이너가 아직 이미지를 참조하면 rmi가 실패합니다 — 컨테이너를 먼저 제거하세요. history는 각 레이어를 만든 명령과 크기를 보여주므로 빌드 최적화에 유용합니다.
# list local images
docker images
docker image ls
# remove an image
docker rmi nginx:latest
docker image rm nginx
# remove all dangling (untagged) images
docker image prune
# remove all unused images
docker image prune -a
# show image history (each layer)
docker history nginx:latest시스템 정보
docker info는 데몬 설정을 보여줍니다: 스토리지 드라이버, 런타임, 레지스트리, 스웜 상태. system df는 회수 가능한 공간을 드러냅니다 — dangling 이미지와 중지된 컨테이너가 디스크를 낭비합니다. --format flag는 Go 템플릿으로 구조화된 출력을 만듭니다.
# docker system-wide info
docker info
docker version
# disk usage breakdown (images, containers, volumes)
docker system df
# detailed disk usage with reclaimable space
docker system df -v
# running containers count
docker ps -q | wc -l
# show docker root directory and storage driver
docker info --format '{{.DockerRootDir}} {{.Driver}}'정리 & 프루닝
prune은 중지/댕글링 리소스를 안전하게 제거합니다. system prune -a는 컨테이너가 참조하지 않는 이미지도 제거합니다. --volumes를 추가하면 컨테이너가 사용하지 않는 볼륨까지 삭제합니다 — 되돌릴 수 없는 데이터 손실이므로 프로덕션에서는 신중히 쓰세요.
# remove stopped containers
docker container prune
# remove dangling images
docker image prune
# remove unused volumes (CAUTION: data loss)
docker volume prune
# remove unused networks
docker network prune
# remove everything unused at once
docker system prune
# also remove volumes (very aggressive)
docker system prune -a --volumes도움말 보기
Docker는 커맨드를 관리 네임스페이스로 묶습니다(docker image, docker container, docker network, docker volume). 구형(docker rmi)과 신형(docker image rm) 모두 동작합니다. 서브커맨드에 --help를 붙이면 flag와 사용법이 나옵니다.
# list all commands
docker --help
docker help
# help for a specific command
docker run --help
docker image --help
# list management commands (grouped)
docker image --help
docker container --help
docker network --help
# show daemon config
docker info
# command reference online
# https://docs.docker.com/reference/이미지 관리
이미지 풀
태그는 변경 가능한 라벨입니다 — 같은 태그가 시간이 지나면 다른 이미지를 가리킬 수 있습니다. 재현 가능한 배포를 위해서는 다이제스트(@sha256:...)로 고정하세요. --platform으로 풀면 다른 아키텍처용 이미지를 가져올 수 있어, x86 호스트에서 ARM 빌드에 유용합니다.
# pull latest tag
docker pull nginx
# pull specific tag
docker pull nginx:1.25-alpine
# pull all tags of a repository
docker pull -a alpine
# pull from a different registry
docker pull ghcr.io/user/repo:tag
# pull by digest (immutable, reproducible)
docker pull nginx@sha256:abc123...
# pull multiple platforms (multi-arch)
docker pull --platform linux/arm64 nginx이미지 빌드
마지막의 .이 빌드 컨텍스트입니다 — 데몬에 전송되는 파일들이죠. .dockerignore로 작게 유지하면 빌드가 빨라집니다. --no-cache는 디버깅 시 새로운 레이어를 강제합니다. BuildKit은 멀티스테이지 캐싱, SSH 마운트, 시크릿 마운트를 가능하게 합니다.
# build from Dockerfile in current dir, tag it
docker build -t myapp:1.0 .
# build with a different Dockerfile name
docker build -f Dockerfile.prod -t myapp:prod .
# build with build args
docker build --build-arg VERSION=1.2.3 -t myapp .
# build with no cache
docker build --no-cache -t myapp .
# build for a different platform
docker build --platform linux/arm64 -t myapp:arm .
# build using BuildKit (advanced features)
DOCKER_BUILDKIT=1 docker build -t myapp .이미지 태깅
태그는 같은 이미지 ID를 가리키는 별칭입니다. 흔한 워크플로우는 버전 태그로 빌드한 뒤 latest와 메이저 버전 태그를 추가합니다. 레지스트리 URL로 태깅하면 그 레지스트리로 push할 준비가 됩니다.
# tag a local image
docker tag myapp:1.0 myapp:latest
# tag for pushing to Docker Hub
docker tag myapp:1.0 username/myapp:1.0
# tag for a private registry
docker tag myapp:1.0 registry.local:5000/myapp:1.0
# tag with multiple tags at once
docker tag myapp:1.0 myapp:stable
docker tag myapp:1.0 myapp:1
# tag by digest reference
docker tag myapp@sha256:abc... myapp:pinned이미지 푸시
push하기 전에 이미지를 레지스트리 대상으로 태깅해야 합니다. push는 레지스트리에 없는 레이어만 업로드합니다. 자체 서명 인증서를 쓰는 프라이빗 레지스트리는 /etc/docker/daemon.json의 insecure-registries에 설정하세요.
# login to Docker Hub
docker login
# login to a private registry
docker login registry.local:5000 -u user -p pass
# push to Docker Hub
docker push username/myapp:1.0
# push all tags in a repository
docker push -a username/myapp
# push to private registry
docker push registry.local:5000/myapp:1.0
# logout when done
docker logout이미지 검사
inspect는 상세 JSON을 반환합니다: 아키텍처, OS, 레이어, env, entrypoint, config. history는 각 레이어의 명령과 크기를 드러냅니다 — 이미지 최적화의 기초입니다. manifest inspect는 풀 없이 원격 레지스트리를 확인합니다.
# low-level image metadata (JSON)
docker inspect nginx:latest
# specific field via Go template
docker inspect --format '{{.Arch}} {{.Os}}' nginx
# show image layers and sizes
docker history nginx:latest
# no-trunc to see full command for each layer
docker history --no-trunc nginx:latest
# inspect an image in a registry (manifest)
docker manifest inspect nginx:latest이미지 저장 & 로드
save/load는 이미지 레이어와 히스토리를 보존합니다 — 오프라인 이미지 전송에 맞는 선택입니다. export/import는 단일 레이어로 납작하게 만들어 히스토리를 잃습니다. 온라인 전송에는 tar 파일보다 레지스트리 push/pull을 권합니다.
# save an image to a tar file
docker save -o myapp.tar myapp:1.0
# save multiple images
docker save -o bundle.tar myapp:1.0 nginx:latest
# load an image from a tar file
docker load -i myapp.tar
# pipe between hosts (no intermediate file)
docker save myapp:1.0 | gzip | ssh host 'gunzip | docker load'
# export a container filesystem (not an image)
docker export mycontainer | gzip > fs.tar.gz컨테이너 관리
컨테이너 실행
-it은 -i(stdin 유지)와 -t(tty 할당)를 합쳐 대화형 세션을 만듭니다. --rm은 종료 후 정리합니다 — 일회성 명령에 이상적입니다. --restart unless-stopped은 재부팅에도 살아남지만 수동 중지는 존중합니다.
# run in background with a name and port mapping
docker run -d --name web -p 8080:80 nginx
# run interactively with a terminal
docker run -it --name shell alpine sh
# run and auto-remove on exit
docker run --rm alpine echo hello
# run with a volume
docker run -d -v mydata:/data alpine
# run with environment variables
docker run -d -e MYSQL_ROOT_PASSWORD=secret mysql
# run with a restart policy
docker run -d --restart unless-stopped nginx명령 실행 (exec)
exec은 이미 실행 중인 컨테이너 안에서 새 프로세스를 실행합니다 — 원래 entrypoint는 계속 돕니다. 디버깅, 관리 작업, 일회성 스크립트 실행에 쓰세요. 기본 사용자는 이미지의 USER이며, -u로 덮어씁니다.
# open an interactive shell in a running container
docker exec -it web sh
# run a command and return
docker exec web ls /usr/share/nginx/html
# run as a specific user
docker exec -u root web whoami
# set environment variables for the command
docker exec -e DEBUG=1 web env
# run with a working directory
docker exec -w /tmp web pwd
# run as detached (rarely useful)
docker exec -d web touch /tmp/marker로그 보기
logs는 컨테이너 로깅 드라이버가 캡처한 stdout/stderr를 보여줍니다. docker logs와 통합되려면 애플리케이션은 파일이 아닌 stdout으로 로그를 남겨야 합니다. --since/--until은 RFC3339 타임스탬프나 Go 기간(30m, 2h)을 받습니다.
# follow (tail) logs
docker logs -f web
# show last 100 lines
docker logs --tail 100 web
# show logs since a timestamp
docker logs --since 2024-01-01T00:00:00 web
# show logs from the last 30 minutes
docker logs --since 30m web
# add timestamps to each line
docker logs -t web
# show logs for a specific timeframe
docker logs --since 10m --until 5m web컨테이너 검사
inspect는 설정, 상태, 네트워크, 마운트를 담은 풍부한 JSON을 반환합니다. Go 템플릿으로 특정 필드를 뽑아내면 스크립팅에 매우 유용합니다. LogPath는 json-file 드라이버가 호스트에 로그를 저장하는 위치를 알려줍니다.
# full JSON metadata
docker inspect web
# container IP address
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' web
# container log path (json-file driver)
docker inspect --format '{{.LogPath}}' web
# mounts and volumes
docker inspect --format '{{json .Mounts}}' web
# container state (running, exited, etc.)
docker inspect --format '{{.State.Status}} {{.State.ExitCode}}' web
# all container ports
docker inspect --format '{{json .NetworkSettings.Ports}}' web시작, 중지 & 재시작
start는 중지된 컨테이너를 원래 설정으로 다시 시작합니다. update는 실행 중인 컨테이너의 제약과 재시작 정책을 재생성 없이 수정합니다 — 프로덕션에서 리소스 한도를 조일 때 유용합니다.
# start a stopped container
docker start web
# stop with a custom timeout (seconds)
docker stop -t 30 web
# restart (keeps container intact)
docker restart web
# rename a container
docker rename web webserver
# update container config (e.g. restart policy)
docker update --restart unless-stopped web
# pause/resume (cgroup freezer)
docker pause web
docker unpause web파일 복사
cp은 양방향으로 동작하며 중지된 컨테이너에도 사용할 수 있습니다 — 핫픽스 주입이나 로그 추출에 유용합니다. 고빈도 동기화용은 아니며, 개발 워크플로우에는 바인드 마운트나 볼륨을 쓰세요. tar+exec 트릭은 큰 트리를 효율적으로 스트리밍합니다.
# copy a file from host to container
docker cp file.txt web:/tmp/
# copy from container to host
docker cp web:/etc/nginx/nginx.conf ./nginx.conf
# copy a directory
docker cp ./app web:/usr/src/app
# copy with archive mode (preserves perms)
docker cp -a ./config web:/etc/app
# copy to a stopped container (works too)
docker cp script.sh web:/script.sh
# tar stream from host to container stdin
docker exec -i web tar xzf - -C /app < app.tar.gzDockerfile 기본
FROM — 베이스 이미지
FROM이 첫 명령이며 베이스 레이어를 정의합니다. 공격 표면과 크기를 줄이려면 미니멀 베이스(alpine, distroless, scratch)를 고르세요. 태그는 바뀔 수 있으므로 다이제스트 고정이 재현 가능한 빌드를 보장합니다.
# use an official base image
FROM ubuntu:22.04
# pin a specific digest for reproducibility
FROM ubuntu@sha256:abc123def...
# multi-arch build (buildx picks the host arch)
FROM --platform=$BUILDPLATFORM golang:1.21 AS builder
# use a minimal image
FROM alpine:3.18
# scratch = empty image, for static binaries
FROM scratch
# use a previous build stage
FROM builder AS finalRUN — 명령 실행
RUN마다 레이어가 만들어집니다. 관련 명령을 &&로 묶고 같은 레이어 안에서 정리하면 이미지가 작아집니다. exec 형식(JSON 배열)은 셸을 호출하지 않아 변수 확장이나 체이닝이 안 되지만 — 시그널을 올바르게 처리합니다.
# install packages
RUN apt-get update && apt-get install -y curl
# clean up in the same layer to reduce size
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
# combine commands with && to reduce layers
RUN mkdir -p /app/config && chown 1000:1000 /app/config
# use exec form (preferred) to ensure signals
RUN ["npm", "install"]
# use a shell for variables and chaining
RUN VERSION=1.0 && wget https://example.com/v${VERSION}.tar.gzCOPY & ADD
로컬 파일에는 COPY가 권장됩니다 — 명시적이고 예측 가능합니다. ADD는 매직 기능을 더합니다: URL 가져오기와 tar/zip 자동 압축 해제. 이 매직은 의외의 동작을 일으킬 수 있으니, 압축 해제가 필요할 때만 ADD를 쓰세요. 둘 다 레이어를 만듭니다.
# copy a file into the image
COPY package.json /app/
# copy a directory
COPY src/ /app/src/
# copy with ownership
COPY --chown=node:node package.json /app/
# copy from a previous build stage
COPY --from=builder /app/dist /app/dist
# ADD can fetch URLs and extract archives
ADD https://example.com/app.tar.gz /tmp/
# ADD extracts local tar archives automatically
ADD app.tar.gz /usr/src/WORKDIR
WORKDIR은 이후 명령과 컨테이너의 기본 작업 디렉터리를 설정합니다. 없으면 디렉터리를 만듭니다. RUN 안의 cd보다 항상 WORKDIR을 권합니다 — cd는 레이어 간에 유지되지 않습니다. 명확성을 위해 절대 경 로를 쓰세요.
# set the working directory
WORKDIR /usr/src/app
# subsequent RUN, CMD, COPY use this dir
COPY . .
RUN npm install
# WORKDIR creates the directory if it does not exist
WORKDIR /opt/data/logs
# use a relative path (relative to previous WORKDIR)
WORKDIR sub
# avoid this anti-pattern (use absolute paths)
WORKDIR /app
RUN cd /app && do_something # cd is lost after RUNUSER
USER는 RUN, CMD, ENTRYPOINT의 사용자(및 선택적으로 그룹)를 설정합니다. non-root 실행이 핵심 보안 모범 사례입니다. 사용자는 이미지 안에 존재해야 합니다. 숫자 UID는 이미지 간 이식 가능하고 이름 조회 문제를 피합니다.
# create a non-root user and switch to it
RUN groupadd -r app && useradd -r -g app appuser
USER appuser
# run subsequent instructions as this user
RUN whoami # appuser
# use a numeric UID for portability
USER 1000
# USER in compose/runtime overrides this
USER 1000:1000
# common pattern: node image ships a 'node' user
FROM node:20-alpine
USER node.dockerignore
.dockerignore는 데몬으로 보내지는 빌드 컨텍스트를 줄입니다 — 빠른 빌드, 작은 컨텍스트, .env 같은 시크릿의 이미지 레이어 유출 방지. 문법은 .gitignore와 비슷합니다. 빌드 중 다시 만들어지는 node_modules와 빌드 산출물은 항상 제외하세요.
# .dockerignore — exclude files from the build context
# version control
.git
.gitignore
# dependencies (fetched inside the image)
node_modules
npm-debug.log
# build artifacts
dist
build
*.log
# local env files (NEVER bake secrets)
.env
.env.local
# docker files themselves
Dockerfile
docker-compose*.yml
# OS files
.DS_Store
Thumbs.dbDockerfile 심화
CMD vs ENTRYPOINT
ENTRYPOINT가 실행 파일을 정의하고, CMD는 덮어쓸 수 있는 기본 인수를 제공합니다. 프로세스가 시그널을 직접 받도록 exec 형식(JSON 배열)을 쓰세요 — 셸 형식은 /bin/sh -c로 감싸 정상 종료를 망가뜨립니다. 흔한 패턴: ENTRYPOINT 스크립트 + CMD 기본 인수.
# CMD: default command, easily overridden
CMD ["nginx", "-g", "daemon off;"]
# override at runtime
# docker run myimage nginx -v
# ENTRYPOINT: fixed command, CMD becomes args
ENTRYPOINT ["nginx"]
CMD ["-g", "daemon off;"]
# runtime args append to ENTRYPOINT
# docker run myimage -v -> nginx -v
# shell form (avoid — no signal handling)
CMD nginx -g "daemon off;"
# script as entrypoint that accepts args
ENTRYPOINT ["./entrypoint.sh"]
CMD ["--help"]ENV — 환경 변수
ENV는 빌드와 런타임에 보이는 이미지 수준 변수를 만듭니다. 빌드 전용 값은 ARG로 두어 최종 이미지에 설정이 새지 않게 하세요. exec 형식 CMD/ENTRYPOINT에서는 ${VAR}이 셸에서 확장되지 않으므로 sh -c로 감싸야 합니다.
# set a persistent env var (baked into image)
ENV NODE_ENV=production
ENV PATH=/app/node_modules/.bin:$PATH
# use in subsequent RUN instructions
ENV VERSION=1.2.3
RUN wget https://example.com/v${VERSION}.tar.gz
# multiple in one line
ENV NODE_ENV=production PORT=3000 LOG_LEVEL=info
# override at runtime
# docker run -e NODE_ENV=development myapp
# view env vars of a container
docker exec web env
# reference env vars in CMD
ENV APP_PORT=3000
CMD ["sh", "-c", "node server.js ${APP_PORT}"]ARG — 빌드 인수
ARG 값은 선언한 스테이지의 빌드 동안만 존재합니다. 런타임 컨테이너에는 남지 않으므로 런타임까지 값을 전달하려면 ENV를 쓰세요. FROM 앞에 선언된 ARG는 '전역'이지만 각 스테이지에서 사용하려면 다시 선언해야 합니다.
# declare a build argument with a default
ARG VERSION=latest
FROM base:${VERSION}
# use ARG only during build (not at runtime)
ARG NODE_ENV=production
RUN echo "Building for ${NODE_ENV}"
# multi-stage: ARG must be redeclared per stage
ARG VERSION
FROM base:${VERSION}
ARG VERSION
RUN echo ${VERSION}
# pass at build time
# docker build --build-arg VERSION=1.0 .
# ARG not available in CMD (use ENV to pass through)
ARG PORT=3000
ENV PORT=${PORT}
CMD ["sh", "-c", "serve --port ${PORT}"]EXPOSE
EXPOSE는 문서화입니다 — 포트를 실제로 공개하지 않습니다. 공개는 런타임에 -p(host:container) 또는 Compose의 ports:로 이뤄집니다. EXPOSE는 도구가 의도된 포트를 이해하게 하고 레거시 네트워크에서 자동 링킹을 가능하게 합니다.
# document which port the container listens on
EXPOSE 80
# expose multiple ports
EXPOSE 80 443
# expose with protocol
EXPOSE 53/udp
# EXPOSE does NOT publish the port
# you still need -p at runtime
# docker run -p 8080:80 myapp
# in compose, expose vs ports
# expose: only to linked services
# ports: published to the host
# view exposed ports
docker inspect --format '{{json .Config.ExposedPorts}}' myappLABEL & 메타데이터
LABEL은 이미지에 키-값 메타데이터를 붙입니다. 레지스트리와 도구와의 상호운용성을 위해 OCI org.opencontainers.image.* 라벨을 채택하세요. 라벨은 버전, 소스, 라이선스, CI 빌드 정보 추적에 유용합니다.
# add a label (key=value metadata)
LABEL maintainer="[email protected]"
LABEL version="1.0"
LABEL description="My web app"
# multiple labels in one instruction
LABEL org.opencontainers.image.title="myapp" \
org.opencontainers.image.version="1.0" \
org.opencontainers.image.source="https://github.com/me/myapp"
# view labels
docker inspect --format '{{json .Config.Labels}}' myapp
# filter images by label
docker images --filter "label=version=1.0"
# deprecated: MAINTAINER (use LABEL maintainer instead)
# MAINTAINER Alice <[email protected]>Dockerfile의 VOLUME
VOLUME은 마운트 지점을 선언합니다; 호스트 경로를 바인드하지 않으면 첫 실행 시 Docker가 익명 볼륨을 만듭니다. 그 디렉터리가 상태 있는 데이터를 담는다고 신호합니다. 함정: COPY 뒤에 VOLUME을 선언하면 복사한 파일이 빈 볼륨에 가려질 수 있습니다.
# declare an anonymous volume mount point
VOLUME /data
# multiple mount points
VOLUME /data /config /logs
# at runtime, Docker creates an anonymous volume
# docker run -v mydata:/data myapp (named instead)
# VOLUME in Dockerfile: any files copied to /data
# are copied into the new anonymous volume on first run
# inspect volumes
docker inspect --format '{{json .Mounts}}' myapp
# avoid: VOLUME after COPY can hide your data
COPY ./config /config
VOLUME /config # new empty volume shadows /config멀티스테이지 빌드
기본 멀티스테이지
멀티스테이지 빌드는 최종 산출물만 런타임 이미지로 복사합니다 — 빌드 도구, 소스, 개발 의존성은 빌더 스테이지에 남습니다. 결과: 작고 안전한 런타임 이미지. AS로 스테이지 이름을 붙이면 COPY --from에서 참조할 수 있습니다.
# stage 1: build
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# stage 2: runtime (small)
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]빌드 스테이지 선택
--target은 지정한 스테이지까지만 빌드하고 뒤의 스테이지는 건너뜁니다. 이로써 개발, 테스트, 프로덕션을 위한 단일 Dockerfile이 가능합니다: CI에는 'test'를, 프로덕션에는 'final'을 타깃. BuildKit은 독립적인 스테이지를 자동 병렬화합니다.
# build only up to a named stage
# docker build --target builder -t myapp:dev .
FROM node:20 AS builder
RUN npm ci && npm run build
FROM node:20-alpine AS test
COPY --from=builder /app /app
RUN npm test
FROM nginx:alpine AS final
COPY --from=builder /app/dist /usr/share/nginx/html
# target a specific stage
# docker build --target test .슬림 런타임 이미지
정적 바이너리(Go, Rust)에는 scratch가 공격 표면 0으로 가장 작은 이미지를 만듭니다. HTTPS를 위해 CA 인증서를 추가하세요. Distroless는 루트 CA와 non-root 사용자를 갖춘 미니멀 베이스로, 동적 언어나 셸 없는 런타임에 이상적입니다.
# build stage
FROM golang:1.21 AS builder
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o app -ldflags="-s -w" .
# scratch = empty image, only the static binary
FROM scratch
COPY --from=builder /src/app /app
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
ENTRYPOINT ["/app"]
# result: ~10MB image
# or use distroless for a minimal OS base
FROM gcr.io/distroless/static
COPY --from=builder /src/app /app
ENTRYPOINT ["/app"]컴파일 언어의 빌더 패턴
풀 SDK 이미지에서 컴파일한 뒤 산출물을 런타임 전용 이미지(JRE)로 복사합니다. 이미지가 크게 줄고(JDK 약 600MB vs JRE 약 200MB) 프로덕션에서 빌드 도구가 사라집니다. COPY 전에 의존성을 미리 받아 두면 레이어 캐싱이 좋아집니다.
# stage 1: compile
FROM maven:3.9 AS builder
WORKDIR /build
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn package -DskipTests
# stage 2: runtime with only the JRE
FROM eclipse-temurin:21-jre-alpine
COPY --from=builder /build/target/*.jar /app/app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
# benefits: no JDK, no source, no Maven cache in runtime외부 이미지에서 복사
COPY --from은 어떤 이미지든 소스가 될 수 있습니다 — 빌드 스테이지 없이 여러 베이스에서 도구를 조립할 때 유용합니다. 스테이지는 인덱스(0 기반)로도 참조할 수 있지만 AS 이름 붙이기가 더 명확합니다. 재현성을 위해 외부 이미지는 다이제스트로 고정하세요.
# copy a binary from another image (no build stage needed)
FROM alpine:3.18
COPY --from=nginx:alpine /usr/sbin/nginx /usr/sbin/nginx
COPY --from=nginx:alpine /etc/nginx /etc/nginx
RUN apk add --no-cache libpcre2
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
# use a specific digest for reproducibility
COPY --from=redis:7@sha256:abc... /usr/local/bin/redis-server /usr/local/bin/
# copy from a built stage referenced by index
COPY --from=0 /build/output /appBuildKit 기능
BuildKit은 캐시 마운트(npm/pip 캐시가 이미지를 키우지 않고 빌드 간 유지), 시크릿 마운트(자격 증명이 레이어에 닿지 않음), 프라이빗 리포를 위한 SSH 포워딩, 더 깔끔한 다중 줄 RUN을 위한 heredoc 문법을 열어줍니다. Dockerfile 프론트엔드 버전 고정에는 # syntax 지시문을 추가하세요.
# enable BuildKit
# DOCKER_BUILDKIT=1 docker build .
# syntax directive for latest frontend
# syntax=docker/dockerfile:1
FROM alpine
# mount a cache (persists across builds, not in image)
RUN --mount=type=cache,target=/root/.npm npm ci
# mount a secret (never written to layers)
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
# mount an SSH socket for private repos
RUN --mount=type=ssh git clone [email protected]:me/repo.git
# heredoc for multi-line scripts
RUN <<EOF
set -ex
apk add --no-cache curl
mkdir -p /app/data
EOF볼륨
볼륨 생성 & 사용
네임드 볼륨은 Docker가 관리하며 데이터 영속화에 권장되는 방식입니다. 컨테이너 제거에도 살아남고 호스트 파일시스템 레이아웃과 독립적입니다. :ro 접미사는 읽기 전용 마운트입니다. inspect는 /var/lib/docker/volumes 아래의 디스크 경로를 드러냅니다.
# create a named volume
docker volume create mydata
# use it in a container
docker run -d -v mydata:/data alpine sh -c "sleep 1h"
# inspect the volume
docker volume inspect mydata
# mount read-only
docker run -v mydata:/data:ro alpine ls /data
# mount with a different filesystem (e.g. tmpfs)
docker run --tmpfs /cache alpine
# default volume driver: local
docker volume create --driver local mydata볼륨 목록 & 검사
ls는 네임드 볼륨을 나열하고, inspect는 드라이버와 마운트 지점을 보여줍니다. 어떤 컨테이너가 볼륨을 쓰는지는 ps를 volume으로 필터해 찾습니다. 볼륨은 리눅스 호스트의 /var/lib/docker/volumes/<name>/_data에 있으며 — 호스트에서 직접 수정하지 말고 docker exec로 접근하세요.
# list all volumes
docker volume ls
# filter by name
docker volume ls -q --filter name=mydata
# show volume details (driver, mountpoint, options)
docker volume inspect mydata
# find the on-disk path
docker volume inspect --format '{{.Mountpoint}}' mydata
# find containers using a volume
docker ps -a --filter volume=mydata --format '{{.Names}}'
# check volume disk usage
docker system df -v | grep mydata볼륨 드라이버
local 드라이버는 마운트 옵션으로 NFS, 블록 디바이스, tmpfs를 지원합니다. 클라우드 스토리지(EBS, Azure Disk)에는 플러그인 드라이버를 쓰세요. 드라이버가 스토리지를 추상화해 run 명령을 바꾸지 않고 컨테이너가 호스트 간 이동합니다 — Swarm/Kubernetes의 핵심입니다.
# local driver (default, on host disk)
docker volume create --driver local mydata
# NFS volume
docker volume create --driver local \
--opt type=nfs \
--opt o=addr=10.0.0.5,rw \
--opt device=:/export/data nfsvol
# tmpfs (in-memory, ephemeral)
docker run --tmpfs /cache alpine
# block device
docker volume create --driver local \
--opt type=ext4 \
--opt device=/dev/sdb1 blockvol
# third-party drivers (e.g. cloud)
docker volume create --driver rexray/ebs ebsvol볼륨 백업
임시 컨테이너에 볼륨과 호스트 디렉터리를 함께 마운트하고 내용을 tar로 묶어 백업합니다. 복원은 그 반대입니다. 이 패턴은 어떤 볼륨 드라이버에도 동작하며 자동 백업 스크립트의 기초입니다.
# back up a volume to a tar file
docker run --rm -v mydata:/data -v $(pwd):/backup alpine \
tar czf /backup/mydata.tar.gz -C /data .
# restore a volume from a tar file
docker volume create mydata2
docker run --rm -v mydata2:/data -v $(pwd):/backup alpine \
tar xzf /backup/mydata.tar.gz -C /data
# migrate data between volumes
docker run --rm -v src:/src -v dst:/dst alpine \
cp -a /src/. /dst/
# snapshot using a temporary container
docker run --rm -v mydata:/data alpine ls -la /data볼륨 제거
컨테이너가 참조하는 동안 볼륨은 제거할 수 없습니다(컨테이너를 먼저 제거). prune은 사용 중이 아닌 볼륨만 제거합니다. 볼륨 삭제는 되돌릴 수 없으며 데이터가 영구 손실됩니다. prune 전에 프로덕션 볼륨을 반드시 백업하세요.
# remove a named volume (must not be in use)
docker volume rm mydata
# remove all unused volumes
docker volume prune
# remove volumes older than 24h not used
docker volume prune --filter "until=24h"
# force remove (even if a stopped container referenced it)
docker volume rm -f mydata
# remove with a label filter
docker volume prune --filter "label=temporary"
# CAUTION: data is gone permanently
docker volume rm mydata컨테이너 간 볼륨 공유
여러 컨테이너가 같은 볼륨을 마운트해 상태를 공유할 수 있습니다. --volumes-from은 다른 컨테이너의 볼륨 마운트를 복제합니다 — 사이드카 패턴에 유용합니다. 읽기 전용 소비자에는 :ro를 추가하세요. 동시 쓰기는 조율해 손상을 피하세요; 일부 앱은 잠금이 필요합니다.
# share a volume between two containers
docker run -d --name db -v shared:/data alpine sleep 1h
docker run -d --name app -v shared:/data alpine sleep 1h
# use --volumes-from to copy a container's mounts
docker run -d --name helper --volumes-from db alpine sleep 1h
# read-only shared volume
docker run -d --name reader -v shared:/data:ro alpine sleep 1h
# compose: shared volume across services
# volumes:
# shared:
# services share 'shared' via volumes: ['shared:/data']
# verify both see the same data
docker exec db sh -c "echo hi > /data/msg"
docker exec app cat /data/msg바인드 마운트
기본 바인드 마운트
바인드 마운트는 호스트 경로를 컨테이너에 직접 매핑합니다 — 호스트에서의 수정이 즉시 반영되는 라이브 개발에 이상적입니다. 절대 호스트 경로를 쓰세요. :ro 접미사는 컨테이너가 호스트에 쓰지 못하게 합니다. 현대 문법은 명확성을 위해 --mount를 씁니다.
# bind mount a host directory (modern syntax)
docker run -d --type bind --source $(pwd)/app --target /app nginx
# short form (-v)
docker run -d -v $(pwd)/app:/app nginx
# absolute host path required
docker run -v /home/me/app:/app nginx
# mount a single file
docker run -v /home/me/app.conf:/etc/app/app.conf:ro nginx
# mount read-only
docker run -v $(pwd)/app:/app:ro nginx
# compose equivalent
# volumes:
# - ./app:/app읽기 전용 바인드 마운트
읽기 전용 마운트는 컨테이너의 쓰기로부터 호스트 설정을 보호합니다 — 보안에 중요합니다. --read-only는 루트 파일시스템 전체를 불변으로 만들며, /tmp와 로그 디렉터리에는 명시적으로 쓰기 가능한 마운트가 필요합니다. 이는 침해에 대한 컨테이너 강화입니다.
# mount config read-only
docker run -v /etc/myapp:/etc/myapp:ro myapp
# --mount equivalent with explicit type
docker run --mount type=bind,source=/etc/myapp,target=/etc/myapp,readonly myapp
# read-only root filesystem (extra security)
docker run --read-only -v /tmp myapp
# combine read-only root with a writable tmpfs
docker run --read-only --tmpfs /tmp --tmpfs /var/cache myapp
# verify the mount is read-only
docker exec myapp touch /etc/myapp/test # should fail개발 워크플로우
소스 코드를 마운트하면 호스트 수정이 컨테이너에 즉시 반영됩니다. 'node_modules 익명 볼륨' 트릭은 호스트의 빈 node_modules가 이미지에 설치된 의존성을 가려버리는 것을 막습니다. Windows/Mac에서는 파일 감시 신뢰성을 위해 폴링이 필요할 수 있습니다.
# live-reload: mount source, run dev server
docker run -d -p 3000:3000 -v $(pwd)/src:/app/src node:20 \
sh -c "cd /app && npm run dev"
# mount node_modules separately (avoid host override)
docker run -d -v $(pwd):/app -v /app/node_modules node:20 npm start
# compose dev workflow
# services:
# web:
# volumes:
# - ./src:/app/src
# - /app/node_modules # anonymous, isolates deps
# hot reload with file watching (polling for Windows/Mac)
docker run -e CHOKIDAR_USEPOLLING=true -v $(pwd):/app node:20 npm startSELinux & AppArmor 라벨
SELinux 사용 호스트(RHEL/CentOS/Fedora)에서는 바인드 마운트에 :z 또는 :Z 접미사가 필요합니다 — 컨테이너가 접근할 수 있게 호스트 경로의 라벨을 다시 매깁니다. :z는 경로를 컨테이너 간 공유하고, :Z는 프라이빗으로 만듭니다. 접미사를 잊으면 'permission denied' 오류가 납니다.
# SELinux: :z (shared) or :Z (private) suffix
docker run -v /host/path:/container/path:z myapp
docker run -v /host/path:/container/path:Z myapp
# :z labels the host path as shared among containers
# :Z labels it private to this container
# disable SELinux isolation (NOT recommended)
docker run --security-opt label=disable myapp
# AppArmor profile
docker run --security-opt apparmor=docker-default myapp
# custom AppArmor profile
docker run --security-opt apparmor=myprofile myappMount vs Volume vs tmpfs
볼륨: Docker 관리, 이식 가능, 영속 데이터에 최적. 바인드 마운트: 호스트 경로, 개발과 설정 주입에 최적. tmpfs: 메모리 기반, 시크릿과 임시 캐시에 최적. --mount 문법이 -v보다 더 명시적이고 스스로 문서화됩니다.
# named volume (Docker-managed, portable)
docker run -v mydata:/data nginx
# bind mount (host path, host-dependent)
docker run -v /home/me/data:/data nginx
# --mount explicit syntax (recommended)
docker run --mount type=volume,source=mydata,target=/data nginx
docker run --mount type=bind,source=/home/me/data,target=/data nginx
docker run --mount type=tmpfs,target=/cache nginx
# tmpfs (in-memory, ephemeral, fast)
docker run --tmpfs /cache nginx
# tmpfs with size limit
docker run --mount type=tmpfs,target=/cache,tmpfs-size=64m nginxCompose의 바인드 마운트
Compose에서 상대 경로(./html)는 바인드 마운트를 만들고, volumes: 섹션을 참조하는 이름(logs)은 네임드 볼륨을 만듭니다. 맨 경로(/cache)는 익명 볼륨입니다. 긴 형식 문법은 read_only 같은 옵션을 명시적으로 만듭니다.
# docker-compose.yml
services:
web:
image: nginx
volumes:
# relative host path = bind mount
- ./html:/usr/share/nginx/html:ro
# named volume
- logs:/var/log/nginx
# anonymous volume
- /cache
volumes:
logs: # declare named volumes here
# use ~ (tilde) — Compose expands it
volumes:
- ~/config:/etc/app:ro
# long-form syntax with options
volumes:
- type: bind
source: ./html
target: /usr/share/nginx/html
read_only: true네트워킹
브리지 네트워크 (기본값)
기본 브리지 네트워크는 자동 DNS가 없습니다 — 컨테이너가 IP를 써야 합니다. 커스텀 브리지 네트워크는 DNS 기반 서비스 디스커버리를 제공합니다: 컨테이너가 이름으로 서로를 해석합니다. Compose가 프로젝트마다 커스텀 네트워크를 자동 만드는 이유입니다.
# the default bridge network (named 'bridge')
docker run -d --name web nginx
# create a custom bridge network (recommended)
docker network create mynet
# attach a container to a custom network
docker run -d --name web --network mynet nginx
docker run -d --name db --network mynet postgres
# containers on the same custom network can resolve by name
docker exec web ping db # DNS resolves 'db'
# the default bridge does NOT support DNS names
# always use a custom bridge for multi-container apps호스트 네트워크
호스트 네트워킹은 네트워크 네임스페이스를 없앱니다 — 컨테이너가 호스트의 인터페이스와 포트를 공유합니다. 성능은 가장 좋지만 격리와 포트 매핑을 희생합니다. 리눅스에서만 가능하며, Mac/Windows에서는 호스트가 아닌 VM 네트워크로 매핑됩니다.
# use the host's network stack directly (no isolation)
docker run --network host nginx
# host network disables port mapping
# -p is ignored when --network host is used
# useful for performance-sensitive apps
docker run --network host -d myapp
# only works on Linux (not Docker Desktop on Mac/Windows)
# inspect host network
docker network inspect host
# bound to host interfaces — be careful with privileged ports
docker run --network host --cap-add NET_ADMIN myapp오버레이 네트워크 (Swarm)
오버레이 네트워크는 여러 Swarm 노드에 걸쳐 내장 DNS와 함께 안전한 크로스 호스트 통신을 가능하게 합니다. --attachable이면 독립 컨테이너도 오버레이에 참여합니다(디버깅에 유용). 암호화가 노드 간 트래픽을 보호합니다; 민감한 워크로드에는 활성화하세요.
# create an overlay network (requires Swarm mode)
docker network create -d overlay myoverlay
# overlay with encryption
docker network create -d overlay -o encrypted myoverlay
# deploy a service on the overlay
docker service create --network myoverlay --name web nginx
# multi-host communication for Swarm services
# containers on different nodes resolve by service name
# node-local network bridged to overlay
docker network create -d overlay --attachable myoverlay
docker run -d --network myoverlay alpine # standalone container커스텀 네트워크
커스텀 네트워크로 서브넷, 게이트웨이, 격리를 제어합니다. --internal은 외부 인터넷 접근을 막습니다. macvlan은 컨테이너에 물리 LAN에서의 실체를 줍니다(각자 자신의 MAC) — 레거시 앱에 유용하지만 기본적으로 호스트-컨테이너 통신이 끊깁니다.
# create a bridge network with a subnet
docker network create --subnet 172.20.0.0/16 mynet
# assign a static IP
docker run -d --network mynet --ip 172.20.0.10 nginx
# set a custom gateway
docker network create --subnet 172.20.0.0/16 \
--gateway 172.20.0.1 mynet
# restrict to internal only (no external access)
docker network create --internal mynet
# specify a driver and options
docker network create -d bridge \
-o com.docker.network.bridge.name=br0 mynet
# macvlan (container gets a MAC on the physical network)
docker network create -d macvlan \
--subnet 192.168.1.0/24 -o parent=eth0 mymacvlan컨테이너 DNS
Docker 내장 DNS(127.0.0.11)는 사용자 정의 네트워크에서 컨테이너 이름을 해석합니다. 기본 브리지에는 DNS가 없습니다. --dns는 외부 리졸버를 추가하고, --add-host는 정적 항목을 주입합니다. 컨테이너 간 통신에는 IP가 아닌 서비스 이름을 써서 재배포가 DNS를 깨지 않게 하세요.
# containers on custom networks resolve by name
docker network create mynet
docker run -d --name db --network mynet postgres
docker run -it --network mynet alpine nslookup db
# the embedded DNS server is at 127.0.0.11
docker exec web cat /etc/resolv.conf
# add custom DNS servers
docker run --dns 8.8.8.8 alpine nslookup example.com
# add DNS search domains
docker run --dns-search example.com alpine nslookup myhost
# add a host entry (like /etc/hosts)
docker run --add-host myservice:10.0.0.5 alpine ping myservice
# extra hosts in compose
# extra_hosts:
# - "myservice:10.0.0.5"네트워크 검사 & 관리
network connect/disconnect는 실행 중인 컨테이너를 재시작 없이 추가 네트워크에 붙게 합니다 — 사이드카에 유용합니다. inspect는 연결된 컨테이너, 서브넷, 드라이버를 보여줍니다. prune은 컨테이너가 쓰지 않는 네트워크를 제거합니다.
# list all networks
docker network ls
# inspect a network (containers, IPAM, driver)
docker network inspect mynet
# see which containers are on a network
docker network inspect --format '{{range .Containers}}{{.Name}} {{end}}' mynet
# connect a running container to another network
docker network connect mynet2 web
# disconnect a container from a network
docker network disconnect mynet web
# remove an unused network
docker network rm mynet
docker network prune포트 매핑
기본 포트 매핑
-p host:container가 호스트 포트를 컨테이너 포트에 매핑합니다. 호스트 포트를 생략하면 Docker가 고릅니다(docker port로 찾으세요). 각 호스트 포트는 하나의 컨테이너에만 매핑됩니다 — 여러 인스턴스에는 리버스 프록시나 서로 다른 호스트 포트를 쓰세요.
# map host:container
docker run -d -p 8080:80 nginx
# map to a random host port
docker run -d -p 80 nginx
docker port $(docker ps -lq) 80 # find the assigned port
# map multiple ports
docker run -d -p 8080:80 -p 8443:443 nginx
# map the same port on host and container
docker run -d -p 80:80 nginx
# explicit protocol (default tcp)
docker run -d -p 53:53/udp dns
# long form
docker run -d --publish 8080:80 nginx특정 IP에 바인딩
IP 접두사가 포트가 바인딩될 인터페이스를 제어합니다. 127.0.0.1은 서비스를 로컬 전용으로 유지합니다 — 노출하고 싶지 않은 데이터베이스에 필수입니다. 0.0.0.0(기본값)은 모든 인터페이스에 바인딩합니다. 프로덕션에서는 데이터베이스를 항상 localhost에 바 인딩하세요.
# bind to a specific host IP
docker run -d -p 127.0.0.1:8080:80 nginx
# bind to localhost only (not exposed externally)
docker run -d -p 127.0.0.1:5432:5432 postgres
# bind to all interfaces (default)
docker run -d -p 0.0.0.0:8080:80 nginx
# bind to an IPv6 address
docker run -d -p [::1]:8080:80 nginx
# multiple bindings
docker run -d -p 127.0.0.1:8080:80 -p 0.0.0.0:8443:443 nginx
# compose: specify IP
# ports:
# - "127.0.0.1:5432:5432"UDP & SCTP 포트
/udp 또는 /sctp 접미사가 프로토콜을 고르며, 기본값은 TCP입니다. DNS처럼 둘 다 필요한 서비스는 두 매핑을 모두 선언하세요. 포트 범위는 호스트-컨테이너 간 1:1 매핑입니다 — WebRTC, RTP, 패시브 FTP에 유용합니다. 방화벽 규칙이 프로토콜과 일치하도록 하세요.
# UDP port (DNS, syslog, statsd)
docker run -d -p 53:53/udp coredns
# both TCP and UDP
docker run -d -p 53:53/tcp -p 53:53/udp coredns
# SCTP (e.g. telecom signaling)
docker run -d -p 3868:3868/sctp myapp
# range of ports (host range maps to container range)
docker run -d -p 8000-8100:8000-8100 myapp
# UDP range
docker run -d -p 50000-50010:50000-50010/udp myapp
# compose with protocol
# ports:
# - "53:53/udp"포트 범위
포트 범위는 1:1로 매핑됩니다(호스트 8000-8005 → 컨테이너 8000-8005). -P(대문자)는 모든 EXPOSE 포트를 무작위 높은 호스트 포트로 자동 공개합니다 — 빠른 테스트에 유용합니다. 포트가 무작위일 때 실제 매핑은 docker ps로 확인하세요.
# map a range of host ports to container ports
docker run -d -p 8000-8005:8000-8005 myapp
# map host range to a single container port (NOT supported)
# this maps range-to-range only
# random port for each (useful for testing)
docker run -d -p 80 -p 443 nginx
docker port $(docker ps -lq)
# expose a range with EXPOSE (documentation only)
# EXPOSE 8000-8005
# publish all exposed ports at once
docker run -d -P nginx # capital P publishes all EXPOSE ports
# view the random mappings
docker ps --format '{{.Names}} {{.Ports}}'공개 vs 노출
EXPOSE는 의도를 문서화하고, -p가 실제로 공개합니다. Compose에서 expose는 같은 네트워크의 다른 서비스와만 포트를 공유하고, ports는 호스트에 공개합니다. 데이터베이스에서 이 구분이 중요합니다: 내부에는 expose하고, 프로덕션에서는 절대 호스트에 publish하지 마세요.
# Dockerfile: EXPOSE is documentation, NOT a publish
EXPOSE 80 443
# runtime: -p PUBLISHES the port to the host
docker run -d -p 8080:80 nginx
# -P publishes all EXPOSE ports to random host ports
docker run -d -P nginx
# compose: expose vs ports
services:
web:
image: nginx
expose:
- "80" # only to linked services, NOT to host
ports:
- "8080:80" # published to the host
# view exposed (not published) ports
docker inspect --format '{{json .Config.ExposedPorts}}' nginx무작위 포트 매핑
호스트 포트를 생략하면 Docker가 무작위 임시 포트(기본 32768-60999)를 고릅니다. docker port나 docker ps로 찾으세요. 한 호스트에서 동일한 서비스를 스케일링할 때 유용합니다. 리눅스에서는 /proc/sys/net/ipv4/ip_local_port_range로 임시 포트 범위를 조정합니다.
# publish to a random high host port
docker run -d -p 80 nginx
# publish all EXPOSE ports randomly
docker run -d -P nginx
# find the assigned port
docker port <container> 80
docker port <container>
# see mappings in ps output
docker ps --format 'table {{.Names}} {{.Ports}}'
# prefer a range for random allocation
docker run -d -p 30000-40000:80 nginx
# compose: random host port
# ports:
# - "80" # random host port, container port 80환경 변수
환경 변수 설정
-e(또는 --env)는 컨테이너의 환경 변수를 설정합니다. 값 없는 -e VAR은 호스트 셸의 변수를 상속합니다. 민감한 값에는 -e 대신 --env-file이나 Docker 시크릿을 권합니다 — 일반 -e는 docker inspect와 프로세스 목록에 보입니다.
# single variable
docker run -d -e MYSQL_ROOT_PASSWORD=secret mysql
# multiple variables
docker run -d \
-e MYSQL_ROOT_PASSWORD=secret \
-e MYSQL_DATABASE=mydb \
-e MYSQL_USER=app \
mysql
# pass from the host environment
docker run -d -e HOST_PWD mysql
# HOST_PWD in the container = $HOST_PWD on host
# set a variable without a value (passes host value or empty)
docker run -e DEBUG alpine env
# long form
docker run --env MYSQL_ROOT_PASSWORD=secret mysqlEnv 파일
--env-file은 파일에서 변수를 불러와 run 명령을 깨끗하게 유지하고 시크릿을 셸 히스토리 밖에 둡니다. Compose는 compose 파일 자체의 변수 치환을 위해 최상위 .env를 자동 로드합니다. 주석(#)과 빈 줄은 무시되고, 따옴표는 문자 그대로 보존됩니다.
# .env file
# DB_HOST=db
# DB_USER=app
# DB_PASSWORD=secret
# load variables from a file
docker run --env-file .env myapp
# load multiple env files
docker run --env-file .env --env-file .env.local myapp
# Compose reads .env automatically for variable substitution
# and supports env_file per service:
# services:
# web:
# env_file:
# - .env
# - .env.local
# env file with comments and blank lines
docker run --env-file config.env myappDockerfile의 환경 변수
ENV는 변수를 이미지에 구워 넣어 빌드와 런타임에 보입니다. ARG는 빌드 시에만 존재하므로 런타임이 필요하면 ENV로 전환하세요. 구워진 값은 런타임에 -e로 덮어씁니다. 참고: 환경 변수는 docker inspect에 보이므로 시크릿을 저장하지 마세요.
# ENV sets a persistent variable
ENV NODE_ENV=production
ENV PATH=/app/bin:$PATH
# use ARG for build-time only, ENV for runtime
ARG BUILD_VERSION=1.0
ENV APP_VERSION=${BUILD_VERSION}
# view all env vars
docker exec web env
# inspect a specific variable
docker exec web printenv NODE_ENV
# override at runtime
docker run -e NODE_ENV=development myapp
# set via Compose
# environment:
# - NODE_ENV=development
# - DEBUG=true동적 환경 변수 & 치환
셸 확장($(...) 또는 ${VAR})은 Docker가 값을 보기 전에 호스트에서 일어납니다. Compose에서는 ${VAR}이 .env 파일로 치환됩니다. exec 형식 CMD에서는 ${VAR}이 확장되지 않으므로 sh -c로 감싸세요. 바인드 마운트의 올바른 파일 소유권을 위해 호스트 UID를 전달하세요.
# pass a computed value at runtime
docker run -e STARTUP_TIME=$(date +%s) myapp
# use host shell expansion
docker run -e USER_ID=$(id -u) myapp
# Compose variable substitution from .env
# services:
# web:
# environment:
# DB_HOST: ${DB_HOST}
# .env file:
# DB_HOST=db
# Compose with default values
# DB_HOST: ${DB_HOST:-localhost}
# pass the current user for permission matching
docker run -u $(id -u):$(id -g) -e HOME=/tmp myapp
# resolve env at runtime with sh -c (not in exec form)
ENV PORT=3000
CMD ["sh", "-c", "node server.js --port ${PORT}"]Compose 환경
Compose의 environment는 리스트나 맵 문법을 받습니다. env_file은 값을 컨테이너로 불러오고, .env(최상위)는 compose 파일 자체의 ${} 치환에 쓰일 변수를 제공합니다. 변수가 많으면 가독성을 위해 맵 형식을 쓰세요.
# docker-compose.yml
services:
web:
image: myapp
environment:
- NODE_ENV=production
- DEBUG=false
- DB_HOST=db
# map form (cleaner for many vars)
environment:
NODE_ENV: production
DB_HOST: db
db:
image: postgres
env_file:
- .env.db
environment:
POSTGRES_DB: ${DB_NAME} # from .env
# top-level .env for substitution
# DB_NAME=mydb시크릿 관리
시크릿은 /run/secrets 아래 파일로 마운트되며 절대 환경 변수로 취급되지 않고, Swarm에서 전송 중 과 저장 시 암호화됩니다. 이미지에 시크릿을 굽거나(ENV) -e로 전달하지 마세요 — 둘 다 docker inspect와 이미지 레이어로 새어 나옵니다. BuildKit 시크릿 마운트는 빌드 시 자격 증명을 레이어 밖에 둡니다.
# Docker Swarm secrets (encrypted, mounted as files)
echo "supersecret" | docker secret create db_password -
docker service create --secret db_password myapp
# read in the app
# cat /run/secrets/db_password
# Compose secrets (v3.1+)
# services:
# web:
# secrets:
# - db_password
# secrets:
# db_password:
# file: ./secrets/db_password.txt
# BuildKit secret mount (build-time, not in layers)
# RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
# avoid: baking secrets in ENV or -e (visible in inspect)
docker run -e API_KEY=xxx myapp # NOT recommendedDocker Compose 기본
기본 docker-compose.yml
Compose는 단일 YAML 파일로 다중 컨테이너 앱을 정의합니다. services가 각 컨테이너를 기술하고, volumes와 networks는 최상위에서 선언합니다. depends_on이 시작 순서를 제어합니다. docker compose up -d가 모든 것을 백그라운드로 시작합니다.
# docker-compose.yml (Compose spec v2)
services:
web:
image: nginx:alpine
ports:
- "8080:80"
volumes:
- ./html:/usr/share/nginx/html:ro
depends_on:
- db
restart: unless-stopped
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
volumes:
- dbdata:/var/lib/postgresql/data
volumes:
dbdata:
# run: docker compose up -dCompose 커맨드
up은 만들고 시작하고, down은 멈추고 제거합니다. down에 -v를 더하면 볼륨까지 삭제합니다(데이터 손실). exec는 실행 중인 서비스에서 명령을 실행하고, run은 일회성 작업용 새 컨테이너를 시작합니다. --scale은 같은 호스트에서 서비스의 여러 복제본을 띄웁니다.
# start all services (foreground)
docker compose up
# start in background (detached)
docker compose up -d
# rebuild images before starting
docker compose up -d --build
# stop and remove containers (keeps volumes)
docker compose down
# also remove volumes (data loss)
docker compose down -v
# view logs (all services)
docker compose logs -f
# scale a service
docker compose up -d --scale worker=3
# run a one-off command in a service
docker compose exec web sh
docker compose run --rm web python manage.py migrate서비스 의존성
depends_on은 시작 순서를 제어하지만 의존 서비스가 '준비됐다'는 뜻은 아닙니다 — healthcheck와 함께 condition: service_healthy를 써 데이터베이스가 연결을 받을 때까지 기다리세요. service_completed_successfully는 초기화 컨테이너를 기다립니다. 앱은 여전히 연결을 재시도해야 합니다.
services:
web:
image: myapp
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
restart: on-failure
db:
image: postgres
healthcheck:
test: ["CMD", "pg_isready", "-U", "postgres"]
interval: 5s
retries: 5
redis:
image: redis
# conditions: service_started | service_healthy | service_completed_successfullyCompose에서 빌드
build는 소스로부터 이미지를 빌드하는 방법을 정의하고, image가 결과에 태그를 붙입니다. context는 빌더로 전송됩니다(작게 유지). target은 멀티스테이지 빌드 스테이지를 고릅니다. --build는 up 시 재빌드를 강제합니다. 빌드 인수는 빌드 시 값을 전달합니다.
services:
web:
build:
context: ./app
dockerfile: Dockerfile.prod
args:
VERSION: 1.0
target: final
image: myapp:1.0
ports:
- "8080:80"
worker:
build: ./worker # shorthand: context only
image: myworker:1.0
# build and tag
docker compose build
docker compose build --no-cache web
docker compose up -d --buildCompose의 볼륨
상대 경로(./html)는 바인드 마운트이고, 최상위 volumes:에 선언된 이름(logs)은 네임드 볼륨이며, 맨 경로(/cache)는 익명입니다. 네임드 볼륨은 드라이버와 옵션(예: NFS)을 지정할 수 있습니다. Compose는 볼륨 이름에 프로젝트 이름을 접두사로 붙입니다.
services:
web:
image: nginx
volumes:
# named volume
- logs:/var/log/nginx
# bind mount (relative path)
- ./html:/usr/share/nginx/html:ro
# anonymous volume
- /cache
db:
image: postgres
volumes:
- dbdata:/var/lib/lib/postgresql/data
volumes:
logs:
dbdata:
driver: local
driver_opts:
type: nfs
device: ":/export/data"
o: addr=10.0.0.5,rwCompose의 네트워크
Compose는 모든 서비스에 기본 네트워크를 만들지만, 커스텀 네트워크를 정의하면 계층을 격리할 수 있습니다. web이 프론트엔드와 백엔드를 잇습니다. internal: true는 백엔드의 인터넷 접근을 막습니다. 같은 네트워크의 서비스들은 DNS로 서비스 이름으로 서로를 해석합니다.
services:
web:
image: nginx
networks:
- frontend
- backend
db:
image: postgres
networks:
- backend
proxy:
image: traefik
networks:
- frontend
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true # no external access
# custom subnet
networks:
backend:
ipam:
config:
- subnet: 172.28.0.0/16Docker Compose 심화
Compose 프로필
프로필은 선택적 서비스를 그룹화합니다. 프로필이 없는 서비스는 항상 시작되고, 프로필이 있는 서비스는 --profile로 활성화될 때만 시작됩니다. 하나의 compose 파일로 개발, 테스트, 운영을 모두 서비스할 수 있습니다: 환경별로 프로필을 선택적으로 켜세요.
services:
web:
image: nginx
profiles: ["default", "prod"]
debug:
image: nginx
profiles: ["debug"]
ports:
- "8080:80"
test:
image: myapp-test
profiles: ["test"]
# start only default services
docker compose up -d
# start with the debug profile
docker compose --profile debug up -d
# run tests
docker compose --profile test run test
# start multiple profiles
docker compose --profile prod --profile debug up -dCompose 오버라이드
Compose는 로컬 개발 커스터마이징을 위해 docker-compose.yml 위에 docker-compose.override.yml을 자동 로드합니다. 다른 환경에는 여러 -f 파일을 순서대로 전달하세요 — 뒤의 파일이 앞의 것을 덮어씁니다. 기본 설정과 환경별 조정이 깔끔하게 분리됩니다.
# docker-compose.yml (base)
services:
web:
image: myapp:latest
environment:
NODE_ENV: production
# docker-compose.override.yml (auto-loaded for dev)
services:
web:
build: ./app
environment:
NODE_ENV: development
DEBUG: "true"
volumes:
- ./src:/app/src
command: npm run dev
# explicit override file
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
# merge order: later files override earlier ones
# docker compose -f base.yml -f dev.yml -f local.yml upCompose의 헬스체크
Compose의 healthcheck는 Dockerfile의 HEALTHCHECK와 대응됩니다. start_period는 시작 중 유예 시간을 줍니다. healthcheck와 depends_on: condition: service_healthy를 결합하면 서비스가 의존성이 '시작만 된' 게 아니라 실제로 준비될 때까지 기다립니다.
services:
web:
image: nginx
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
db:
image: postgres
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
app:
image: myapp
depends_on:
db:
condition: service_healthy스케일링 & 복제본
--scale은 한 호스트에서 N개의 동일 컨테이너를 띄웁니다 — 서비스가 고정 호스트 포트에 바인딩하면 안 됩니다(무작위 포트 또는 호스트 매핑 없음). deploy.replicas 키는 Swarm이 존중합니다; 일반 Compose에는 --scale을 쓰세요. 스케일된 서비스 앞에는 로드밸런서가 섭니다.
# scale at startup (single host)
docker compose up -d --scale worker=4
# docker-compose.yml with replicas (Compose spec)
services:
worker:
image: myworker
deploy:
replicas: 4
resources:
limits:
cpus: "0.5"
memory: 512M
web:
image: nginx
deploy:
replicas: 2
update_config:
parallelism: 1
delay: 10s
# note: replicas deploy key is for Swarm;
# plain Compose uses --scale
# prevent port conflicts when scaling
docker compose up -d --scale web=3 # web must use random portsCompose 설정 & 검증
config는 병합된 compose 파일(오버라이드와 .env 치환 포함)을 검증하고 렌더링합니다 — 디버깅에 매우 유용합니다. --services, --images, --volumes가 리소스를 목록화합니다. CI에서는 -q로 잘못된 compose 파일에서 빠르게 실패하세요.
# validate and print the merged compose file
docker compose config
# check for errors only
docker compose config -q
# list all services
docker compose config --services
# list all images used
docker compose config --images
# list all volumes
docker compose config --volumes
# render with variable substitution (resolve .env)
docker compose config > rendered.yml
# validate before deploying
docker compose config -q && docker compose up -d다중 Compose 파일
compose 파일을 겹치면 관심사가 분리됩니다: 기본 설정, 환경 오버라이드, 로컬 조정. COMPOSE_FILE(리눅스/Mac은 콜론, Windows는 세미콜론 구분)은 -f 반복을 피하게 합니다. ports 같은 리스트는 덧붙여지고, environment 같은 맵은 키 단위로 병합됩니다.
# base, dev, and prod files
docker compose -f docker-compose.yml -f docker-compose.dev.yml up
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
# COMPOSE_FILE env var (avoids -f repetition)
export COMPOSE_FILE=docker-compose.yml:docker-compose.dev.yml
docker compose up -d
# docker-compose.prod.yml
services:
web:
image: registry.com/myapp:${TAG}
environment:
NODE_ENV: production
deploy:
replicas: 3
# difference files: add/override specific keys
# lists (ports, volumes) are merged; maps (environment) are mergedDocker 레지스트리
로컬 레지스트리 실행
registry:2 이미지가 포트 5000에서 프라이빗 레지스트리를 실행합니다. 이미지를 영속화하려면 볼륨을 마운트하세요. 원격 호스트나 HTTPS를 위해서는 TLS 인증서를 설정하거나 /etc/docker/daemon.json의 insecure-registries에 레지스트리를 추가하세요. v2 API로 curl로 리포지터리 목록을 볼 수 있습니다.
# run the official registry image
docker run -d -p 5000:5000 --name registry \
-v registrydata:/var/lib/registry \
--restart always \
registry:2
# tag and push to it
docker tag myapp:1.0 localhost:5000/myapp:1.0
docker push localhost:5000/myapp:1.0
# pull from it
docker pull localhost:5000/myapp:1.0
# list repositories in the registry
curl http://localhost:5000/v2/_catalog
# list tags for a repository
curl http://localhost:5000/v2/myapp/tags/list프라이빗 레지스트리로 푸시
이미지는 push 전에 레지스트리 호스트로 태깅되어야 합니다. 자체 서명 인증서 레지스트리는 호스트를 insecure-registries에 추가하고 데몬을 재시작하세요(프로덕션에서는 권장되지 않음 — 실제 CA나 내부 CA를 쓰세요). push -a는 리포지터리의 모든 태그를 업로드합니다.
# tag with the registry URL
docker tag myapp:1.0 registry.local:5000/myapp:1.0
# login
docker login registry.local:5000
# push
docker push registry.local:5000/myapp:1.0
# push all tags
docker push -a registry.local:5000/myapp
# verify it landed
curl http://registry.local:5000/v2/myapp/tags/list
# self-signed cert: configure the daemon
# /etc/docker/daemon.json:
# { "insecure-registries": ["registry.local:5000"] }
# then: systemctl restart docker프라이빗 레지스트리에서 풀
전체 이미지 이름을 지정해 프라이빗 레지스트리에서 풀합니다. 로그인 자격 증명은 ~/.docker/config.json에 저장됩니다(보안을 위해 credential helper 사용). CI/CD에서는 자격 증명을 시크릿으로 저장하고 풀 전에 로그인하세요. 재현 가능한 배포를 위해 다이제스트로 고정하세요.
# login first (credentials cached in ~/.docker/config.json)
docker login registry.local:5000
# pull by full name
docker pull registry.local:5000/myapp:1.0
# pull by digest (immutable)
docker pull registry.local:5000/myapp@sha256:abc123...
# use in Compose
# services:
# web:
# image: registry.local:5000/myapp:1.0
# logout
docker logout registry.local:5000
# check stored credentials
cat ~/.docker/config.json레지스트리 인증
레지스트리는 htpasswd basic 인증이나 토큰(OAuth) 서버로 보호합니다. TLS에는 인증서를 마운트하고 443에서 리슨하세요. credential helper(credsStore)는 평문 config.json 대신 OS 키체인에 비밀번호를 저장합니다 — 공유 머신이나 CI 머신에 필수입니다.
# htpasswd-based auth
mkdir -p auth
docker run --entrypoint htpasswd httpd:2 -Bbn user password > auth/htpasswd
# run registry with auth
docker run -d -p 5000:5000 --name registry \
-v $(pwd)/auth:/auth \
-e REGISTRY_AUTH=htpasswd \
-e REGISTRY_AUTH_HTPASSWD_REALM=Registry \
-e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd \
registry:2
# login now required
docker login localhost:5000
# token-based auth (OAuth, JWT) for enterprise
# configure REGISTRY_AUTH=token with an auth server
# credential helpers (avoid storing in config.json)
# "credsStore": "secretservice" (Linux)
# "credsStore": "osxkeychain" (Mac)
# "credsStore": "wincred" (Windows)레지스트리 API
Registry HTTP API v2로 레지스트리 관리를 스크립팅할 수 있습니다. _catalog가 리포를 나열하고, manifests가 이미지 레이어를 기술합니다. 삭제에는 REGISTRY_STORAGE_DELETE_ENABLED=true가 필요하며 매니페스트를 제거합니다 — 블롭은 가비지 컬렉션(registry garbage-collect)이 정리합니다.
# list all repositories
curl http://localhost:5000/v2/_catalog
# list tags for a repo
curl http://localhost:5000/v2/myapp/tags/list
# get a manifest
curl -H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
http://localhost:5000/v2/myapp/manifests/1.0
# delete a manifest (by digest)
curl -X DELETE \
http://localhost:5000/v2/myapp/manifests/sha256:abc123...
# enable delete API
# -e REGISTRY_STORAGE_DELETE_ENABLED=true
# check if a blob exists
curl -I http://localhost:5000/v2/myapp/blobs/sha256:abc...가비지 컬렉션
매니페스트를 삭제해도 가비지 컬렉션이 실행되기 전까지 고아 블롭이 남습니다. 사용 중인 레이어를 수집하지 않도록 레지스트리를 중지(또는 --dry-run 사용)하세요. 프로덕션에서는 삭제되거나 대체된 이미지로부터 디스크를 회수하도록 GC를 정기 예약하세요. config.yml 경로가 레지스트리의 설정 파일입니다.
# run garbage collection on a registry
docker exec -it registry \
garbage-collect --dry-run /etc/docker/registry/config.yml
# actual collection (stop the registry first for consistency)
docker stop registry
docker run --rm -v registrydata:/var/lib/registry \
-v /path/config.yml:/etc/docker/registry/config.yml \
registry:2 garbage-collect /etc/docker/registry/config.yml
docker start registry
# delete unreferenced blobs after manifest deletion
# schedule GC as a cron job for production registries
# view disk usage
docker exec registry du -sh /var/lib/registryDocker Hub
로그인 & 로그아 웃
비밀번호보다 액세스 토큰을 권합니다 — 취소 가능하고 스코프가 있습니다. --password-stdin은 stdin에서 읽어 셸 히스토리와 프로세스 목록에 비밀번호가 남지 않게 합니다. credential helper를 설정해 평문 config.json 대신 OS 키체인에 자격 증명을 저장하세요.
# interactive login (prompts for username/password)
docker login
# login with a token (recommended over password)
docker login -u username -p dckr_pat_xxxxx
# login via stdin (avoids shell history)
echo "dckr_pat_xxxxx" | docker login -u username --password-stdin
# logout
docker logout
# credentials stored in ~/.docker/config.json
# or OS keychain via credential helper
# create an access token on Docker Hub
# Account Settings -> Security -> New Access Token이미지 검색
docker search는 CLI에서 Docker Hub를 조회하며 stars, 공식 여부, 자동 빌드 필터가 있습니다. 공식 이미지(library/nginx)는 Docker가 검증합니다 — 베이스로 선호하세요. 웹 UI는 OS, 아키텍처, 카테고리별 더 풍부한 필터를 제공합니다.
# search Docker Hub from the CLI
docker search nginx
# filter by stars
docker search --filter stars=100 nginx
# only official images
docker search --filter is-official nginx
# only automated builds
docker search --filter is-automated nginx
# limit results
docker search --limit 5 nginx
# show full description (no truncation)
docker search --no-trunc nginx
# search on the web for richer filtering
# https://hub.docker.com/search?q=nginxDocker Hub로 푸시
이미지를 username/repo:tag로 태깅한 뒤 push하면 Docker Hub에 공개됩니다. 리포지터리는 첫 push에서 자동 생성됩니다(기본 공개). push -a는 모든 태그를 업로드합니다. 무료 계정은 프라이빗 리포 하나를 얻고, 유료 플랜은 더 많습니다. 리포 가시성은 Hub 웹 UI에서 설정합니다.
# tag with your username
docker tag myapp:1.0 username/myapp:1.0
# also tag as latest
docker tag username/myapp:1.0 username/myapp:latest
# login
docker login
# push (creates the repo if it doesn't exist)
docker push username/myapp:1.0
docker push username/myapp:latest
# push all tags
docker push -a username/myapp
# make the repo private on Docker Hub
# (Hub web UI -> Repository -> Settings -> Make Private)자동 빌드
Docker Hub의 autobuild는 git 리포와 연결되어 push마다 빌드합니다. 현대 워크플로우는 더 많은 제어, 캐싱, 멀티 아치 빌드를 제공하는 GitHub Actions + buildx + push를 선호합니다. Hub autobuild 는 단순 프로젝트에 저비용 옵션으로 남아 있습니다.
# connect a GitHub/Bitbucket repo to Docker Hub
# Hub web UI -> Create -> Build Rule
# build rule examples:
# Source: github.com/me/myapp Branch: main
# Dockerfile location: /Dockerfile
# Image tag: latest
# trigger a build via webhook
curl -H "Content-Type: application/json" \
--data '{"build": true}' \
https://hub.docker.com/api/build/v1/source/.../trigger/.../call/
# build context with multiple tags and stages
# Source: Branch main -> Tag: branch-main
# Source: Tag v1.0 -> Tag: 1.0, latest
# Autobuild triggers on git push
# (deprecated in favor of GitHub Actions)조직 & 팀
조직은 역할 기반 접근으로 팀 전체가 리포지터리를 공유하게 합니다. 팀은 리포별 권한(read, write, admin)을 가집니다. 서비스 계정은 CI/CD를 위한 비개인 토큰을 제공합니다 — 개인에게 영향 없이 취소·교체할 수 있습니다. orgname/repo 네임스페이싱을 쓰세요.
# create an organization on Docker Hub
# (web UI: Create Organization)
# create a team and add members
# Org -> Teams -> Create Team -> Add Members
# assign repository permissions per team
# Repository -> Permissions -> Add Team
# Read-only, Read-write, Admin
# create a service account token for CI
# Org -> Service Accounts -> New Service Account
# use the token in CI: docker login -u tokenname -p token
# team namespaces: orgname/repo
docker tag myapp orgname/myapp:1.0
docker push orgname/myapp:1.0이미지 신뢰 (DCT)
Docker Content Trust(DCT)는 Notary로 이미지 태그에 서명해, 풀한 이미지가 게시자가 push한 것임을 보장합니다. DOCKER_CONTENT_TRUST=1로 활성화합니다. DCT가 켜지면 서명된 이미지만 풀/푸시할 수 있습니다. 서명 키를 신중히 관리하세요 — 잃어버리면 자신의 이미지에 갇힐 수 있습니다.
# enable Docker Content Trust (signing)
export DOCKER_CONTENT_TRUST=1
# push signs the image automatically
docker push username/myapp:1.0
# pull refuses unsigned images when DCT is on
docker pull username/myapp:1.0
# disable for a single command
DOCKER_CONTENT_TRUST=0 docker pull unsigned/myapp:1.0
# generate delegation keys
docker trust key generate alice
# add a signer to a repository
docker trust signer add --key alice.pub alice username/myapp
# view signatures
docker trust inspect username/myapp:1.0
# revoke and rotate keys via the notary CLI헬스체크
기본 헬스체크
헬스체크는 주기적으로 명령을 실행합니다; exit 0이면 건강, 0이 아니면 불건강입니다. 컨테이너는 'starting'으로 시작해 재시도가 성공하면 'healthy', 재시도가 실패하면 'unhealthy'가 됩니다. start_period가 부팅 중 유예 시간을 줍니다. 헬스 상태가 Swarm 재시작 결정을 이끕니다.
# add a healthcheck at runtime
docker run -d --name web \
--health-cmd="curl -f http://localhost/ || exit 1" \
--health-interval=30s \
--health-timeout=5s \
--health-retries=3 \
--health-start-period=10s \
nginx
# check health status
docker inspect --format '{{.State.Health.Status}}' web
# view health check log (last 5 results)
docker inspect --format '{{json .State.Health.Log}}' web | jq
# states: starting | healthy | unhealthy | noneDockerfile의 헬스체크
Dockerfile의 HEALTHCHECK는 검사를 이미지에 굽습니다. 앱이 실제로 서빙하는지 확인하는 가장 가벼운 검사를 쓰세요 — HTTP에는 curl -f나 wget --spider, Postgres에는 pg_isready. HEALTHCHECK NONE은 상속된 검사를 비활성화합니다. 너무 넓은 검사는 거짓 'unhealthy' 플래핑을 일으킵니다.
FROM nginx:alpine
# basic healthcheck (exec form)
HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=10s \
CMD curl -f http://localhost/ || exit 1
# using wget (alpine)
HEALTHCHECK CMD wget --spider -q http://localhost/ || exit 1
# postgres ships a ready check
HEALTHCHECK CMD pg_isready -U postgres
# disable a healthcheck inherited from the base image
HEALTHCHECK NONE
# verify
docker inspect --format '{{.Config.Healthcheck}}' myapp헬스체크 옵션
interval은 검사 빈도, timeout은 각 검사의 상한, retries는 연속 실패 임계값입니다. start_period는 부팅 중 실패를 무시해 앱이 예열되는 동안 거짓 'unhealthy'를 막습니다. 부하 아래 플래핑 없이 실제 장애를 빠르게 잡도록 조정하세요.
# full set of options
HEALTHCHECK \
--interval=30s \ # time between checks (default 30s)
--timeout=5s \ # max time per check (default 30s)
--retries=3 \ # failures to mark unhealthy (default 3)
--start-period=30s \ # boot grace period (default 0s)
CMD curl -f http://localhost/
# interval: how often to run
# timeout: if a check exceeds this, it's a failure
# retries: consecutive failures before unhealthy
# start-period: failures during this don't count
# compose form
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s헬스 상태 검사
ps는 상태 옆에 (healthy)/(unhealthy)를 보여줍니다. Health.Log는 최근 5개 검사 출력을 기록합니다 — 검사가 왜 실패하는지 디버깅에 매우 유용합니다. exec으로 검사 명령을 수동 실행해 실제 오류를 확인하세요. ps를 health로 필터하면 아픈 컨테이너를 빨리 찾습니다.
# current status
docker inspect --format '{{.State.Health.Status}}' web
# last 5 check results
docker inspect --format '{{range .State.Health.Log}}\
{{.ExitCode}} {{.Output}}{{end}}' web
# show in ps (status column shows (healthy)/(unhealthy))
docker ps
# filter containers by health
docker ps --filter "health=unhealthy"
# troubleshoot a failing check
docker inspect --format '{{json .State.Health.Log}}' web | jq
# run the check command manually
docker exec web curl -f http://localhost/Compose 헬스체크
Compose의 healthcheck는 Dockerfile을 따릅니다. test는 배열(exec 형식)이나 CMD-SHELL 문자열을 받습니다. disable: true는 상속된 검사를 제거합니다. healthcheck와 depends_on: condition: service_healthy를 짝지어 서비스가 의존성이 '시작만 된' 게 아니라 실제로 준비될 때까지 기다리게 하세요.
services:
web:
image: nginx
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
db:
image: postgres
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
retries: 5
app:
image: myapp
depends_on:
db:
condition: service_healthy
web:
condition: service_healthy
# disable a healthcheck
debug:
image: nginx
healthcheck:
disable: true헬스체크 모범 사례
핵심 의존성(DB, 캐시)을 검증하는 실제 /healthz 엔드포인트를 검사하세요 — 맨 TCP 검사는 앱이 망가진 상태에서도 통과할 수 있습니다. 검사는 가볍고 빠르게 유지하세요; 매 interval마다 실행 됩니다. 느리게 시작하는 런타임(JVM, Rails)에는 start_period를 써 부팅 중 unhealthy로 표시되지 않게 하세요.
# check the actual app endpoint, not just TCP
HEALTHCHECK CMD curl -f http://localhost/healthz || exit 1
# include a /healthz endpoint in your app
# that verifies DB and cache connectivity
# keep checks fast (under timeout)
HEALTHCHECK --timeout=3s CMD curl -f http://localhost/healthz
# avoid heavy checks — they run every interval
# don't run migrations or full DB queries
# use start-period for slow starters (Java, Rails)
HEALTHCHECK --start-period=60s CMD ...
# for Swarm, health enables auto-restart of unhealthy tasks
# combine with restart policies and update_config
# example app endpoint (Express)
# app.get('/healthz', (req, res) => res.send('ok'))리소스 한도
메모리 한도
--memory는 하드 한도를 설정하며 초과하면 OOM 킬이 됩니다. --memory-swap은 메모리+스왑 합계를 제한하며, 메모리와 같게 설정하면 스왑이 비활성화됩니다. --memory-reservation은 커널에 주는 소프트 힌트입니다. 지연 민감 워크로드에서는 예측 가능한 성능을 위해 스왑을 끄세요.
# limit to 512MB of memory
docker run -d --memory="512m" nginx
# memory + swap (swap = memory + swap allowance)
docker run -d --memory="512m" --memory-swap="1g" nginx
# soft limit (hint to the kernel, may be exceeded)
docker run -d --memory-reservation="256m" nginx
# disable swap (swap = memory, no extra)
docker run -d --memory="512m" --memory-swap="512m" nginx
# OOM behavior: kill the container (default)
docker run -d --memory="512m" --oom-kill-disable nginx
# verify limits
docker inspect --format '{{.HostConfig.Memory}}' <container>CPU 한도
--cpus는 코어의 비율로 CPU 한도를 설정합니다(1.5 = 1.5코어). --cpu-shares는 경합 시 쓰이는 상대 가중치이지 하드 캡이 아닙니다. --cpuset-cpus는 컨테이너를 특정 코어에 고정해 성능 격리에 유용합니다. quota/period는 저수준 cgroup 형태입니다.
# limit to 1 CPU (1.0 = one full core)
docker run -d --cpus="1.0" nginx
# limit to 1.5 CPUs
docker run -d --cpus="1.5" nginx
# CPU shares (relative weight, default 1024)
docker run -d --cpu-shares=512 nginx
# pin to specific CPU cores (0,1)
docker run -d --cpuset-cpus="0,1" nginx
# pin to cores 0-3
docker run -d --cpuset-cpus="0-3" nginx
# quota/period form (100000us per 100000us = 1 CPU)
docker run -d --cpu-quota=50000 --cpu-period=100000 nginx메모리 & 스왑 동작
memory-swap은 메모리 + 스왑의 합계입니다. 메모리와 같게 설정하면 스왑이 꺼집니다. -1은 무제한 스왑을 허용합니다. Swappiness(0-100)는 커널의 스왑 경향을 제어합니다; 낮은 값이 RAM에 페이지를 유지하는 것을 선호합니다. 커널 메모리 한도는 고급이고 드뭅니다.
# memory limit, swap disabled
docker run -d -m 512m --memory-swap 512m nginx
# memory limit, 512m extra swap
docker run -d -m 512m --memory-swap 1g nginx
# unlimited swap (limited memory)
docker run -d -m 512m --memory-swap -1 nginx
# swappiness (0-100, lower = less swapping)
docker run -d -m 512m --memory-swappiness=10 nginx
# kernel memory limit (advanced, rarely needed)
docker run -d --kernel-memory="100m" nginx
# verify swap settings
docker inspect --format '{{.HostConfig.MemorySwap}}' <container>Compose 리소스 한도
deploy.resources.limits는 하드 캡이고, reservations는 소프트 보장입니다(스케줄링에 사용). Swarm은 이를 네이티브로 존중합니다. 일반 Compose(비 Swarm)에는 v2 형식의 최상위 mem_limit과 cpus를 쓰세요. reservation은 유휴일 때도 컨테이너가 최소량을 주장하게 합니다.
services:
web:
image: nginx
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
reservations:
cpus: "0.25"
memory: 256M
worker:
image: myworker
mem_swappiness: 10
memswap_limit: 1g
cpus: 2.0
# limits = hard caps; reservations = soft guarantees
# Swarm honors deploy.resources
# plain Compose: use top-level mem_limit, cpus (v2 compat)OOM & 재시작 동작
메모리가 소진되면 커널의 OOM 킬러가 희생자를 고릅니다. oom-kill-disable은 컨테이너를 보호하지만 호스트를 죽일 수 있습니다 — 호스트 메모리 한도와 함께만 쓰세요. oom-score-adj는 선택을 편향시킵니다: 양수 = 먼저 죽음, 음수 = 보호. 재시작 진단에는 OOMKilled를 확인하세요.
# default: OOM kills the container, restart policy restarts it
docker run -d --memory=512m --restart unless-stopped nginx
# disable OOM kill for this container (risky)
docker run -d --memory=512m --oom-kill-disable nginx
# set OOM score adjustment (higher = killed first)
docker run -d --oom-score-adj=500 nginx
# protect a critical container (killed last)
docker run -d --oom-score-adj=-500 nginx
# verify restart count
docker inspect --format '{{.RestartCount}}' <container>
# check if OOM-killed
docker inspect --format '{{.State.OOMKilled}}' <container>리소스 사용량 검사
docker stats는 컨테이너별 CPU, 메모리, 네트워크, 디스크 IO를 실시간 스트리밍합니다 — 빠른 분류의 필수 도구. --no-stream은 스크립트용 단일 스냅샷을 줍니다. 더 깊은 분석에는 /sys/fs/cgroup을 긁거나 cAdvisor로 Prometheus 메트릭을 노출하세요. 한도와 사용량을 비교해 적정 크기를 잡으세요.
# live resource stats (CPU, memory, network, IO)
docker stats
# specific container
docker stats web
# one snapshot (no streaming)
docker stats --no-stream
# custom format
docker stats --format "table {{.Name}} {{.CPUPerc}} {{.MemUsage}}"
# container cgroup details
docker exec web cat /sys/fs/cgroup/memory/memory.usage_in_bytes
docker exec web cat /sys/fs/cgroup/cpu/cpu.stat
# inspect configured limits
docker inspect --format '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}' web보안
Non-root 사용자
non-root 실행은 앱이 침해됐을 때 피해 범위를 제한합니다. Dockerfile에서 전용 사용자를 만들고 USER로 전환하세요. 특권 포트를 바인드해야 한다면 root로 실행하는 대신 리버스 프록시(nginx)나 NET_BIND_SERVICE capability를 부여하세요.
# Dockerfile: create and use a non-root user
FROM node:20-alpine
RUN addgroup -S app && adduser -S app -G app
USER app
WORKDIR /app
COPY --chown=app:app . .
CMD ["node", "server.js"]
# at runtime, override the user
docker run -u 1000:1000 myapp
# verify the current user
docker exec web id
# bind to privileged ports? Use capabilities or a reverse proxy
# non-root cannot bind to ports < 1024 without NET_BIND_SERVICE
# distroless images ship a non-root user by default
FROM gcr.io/distroless/nodejs20
USER nonroot읽기 전용 루트 파일시스템
읽기 전용 루트 파일시스템은 침해 시 공격자가 멀웨어를 쓰거나 설정을 바꾸지 못하게 합니다. 스크래치 디렉터리(/tmp, /cache)에는 tmpfs를, 영속 데이터에는 볼륨을 짝지으세요. 앱이 이를 전제로 설계되어야 합니다 — 일부 프레임워크는 의외의 경로에 쓰며 tmpfs 마운트가 필요합니다.
# make the root filesystem read-only
docker run --read-only nginx
# allow writes only to specific dirs via tmpfs
docker run --read-only --tmpfs /tmp --tmpfs /var/cache nginx
# combine with a writable volume for persistent data
docker run --read-only -v appdata:/data --tmpfs /tmp myapp
# compose form
services:
web:
image: nginx
read_only: true
tmpfs:
- /tmp
- /var/cache/nginx
# apps must be designed to not write outside allowed pathsLinux Capabilities
기본적으로 Docker는 제한된 리눅스 capability 집합을 부여합니다. ALL을 drop하고 앱에 필요한 것만 다시 추가하세요 — 최소 권한 원칙입니다. --privileged는 모든 capability와 호스트 디바이스 접근을 부여합니다; 신뢰된 컨테이너 런타임 외에는 완전히 피하세요. NET_RAW는 기본으로 drop하세요.
# drop all capabilities, add only what's needed
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx
# add a specific capability
docker run --cap-add=SYS_PTRACE myapp
# common capabilities to drop (rarely needed by apps)
# CHOWN, DAC_OVERRIDE, FOWNER, KILL, NET_RAW, SETGID, SETUID
# NET_RAW is often safe to drop (prevents raw sockets/ping)
docker run --cap-drop=NET_RAW myapp
# privileged = all capabilities + host access (AVOID)
docker run --privileged myapp # DANGEROUS
# inspect capabilities
docker inspect --format '{{json .HostConfig.CapAdd}}' <container>Seccomp & AppArmor
Seccomp는 컨테이너가 할 수 있는 시스콜을 필터링합니다 — 기본 프로필이 약 44개의 위험한 시스콜을 차단합니다. AppArmor는 파일과 capability 접근을 구속합니다. no-new-privileges는 setuid 바이너리가 새 권한을 얻지 못하게 합니다 — 저비용 고가치의 강화입니다.
# default seccomp profile blocks dangerous syscalls
docker run --security-opt seccomp=default.json nginx
# custom seccomp profile
docker run --security-opt seccomp=/path/to/profile.json nginx
# disable seccomp (NOT recommended)
docker run --security-opt seccomp=unconfined nginx
# AppArmor profile
docker run --security-opt apparmor=docker-default nginx
# custom AppArmor profile
docker run --security-opt apparmor=myprofile nginx
# no-new-privileges (prevents setuid escalation)
docker run --security-opt no-new-privileges nginx이미지 스캐닝
push 전에 알려진 취약점(CVE)을 스캔하세요. docker scout(이전의 snyk 기반 docker scan)가 내장되어 있습니다. Trivy와 Grype가 인기 대안입니다. 고심각도 CVE가 있는 이미지를 차단하도록 CI에 스캔을 통합하세요. 새 CVE가 공개되면 주기적으로 베이스 이미지를 재스캔하세요.
# docker scout (built-in, replaces docker scan)
docker scout cves myapp:1.0
# scan a local image
docker scout cves --format json myapp:1.0
# compare two images
docker scout compare myapp:1.0 --to myapp:1.1
# Trivy (third-party, popular)
trivy image myapp:1.0
# Grype (third-party)
grype myapp:1.0
# scan a Dockerfile for bad practices
docker scout policy myapp --only-stream-default
# integrate scanning in CI
# - build image
# - scan
# - fail the pipeline on HIGH/CRITICAL CVEsDocker Content Trust & 강화
Content Trust는 서명된 이미지만 풀하게 합니다. 데몬을 강화하세요: 컨테이너 간 통신 비활성화(icc=false), 데몬 재시작에도 컨테이너가 살아남게 하는 live-restore 활성화, 컨테이너 root를 non-root 호스트 UID로 매핑하는 user namespaces(userns-remap) 활성화로 더 강한 격리를 얻습니다.
# enable content trust (image signing)
export DOCKER_CONTENT_TRUST=1
docker pull myapp:1.0 # refuses unsigned
# sign on push
docker push myapp:1.0 # signs with your key
# daemon hardening in /etc/docker/daemon.json
# {
# "userland-proxy": false,
# "live-restore": true,
# "no-new-privileges": true,
# "icc": false # disable inter-container communication on default bridge
# }
# restrict registry access
# "registry-mirrors": [],
# "insecure-registries": []
# audit the daemon
docker info --format '{{json .SecurityOptions}}'
# use user namespaces for host UID isolation
# /etc/docker/daemon.json: "userns-remap": "default"로깅 & 모니터링
로그 보기
docker logs는 로깅 드라이버가 캡처한 stdout/stderr를 읽습니다. docker logs와 통합되려면 앱은 파일이 아닌 stdout으로 로그를 남겨야 합니다. --tail과 --since가 출력을 제한합니다. Compose logs는 서비스들에 걸쳐 집계합니다. 기본 json-file 드라이버는 상한을 두지 않으면 무한히 커집니다.
# follow logs
docker logs -f web
# last 100 lines
docker logs --tail 100 web
# since a timestamp
docker logs --since 30m web
# with timestamps
docker logs -t web
# a specific time range
docker logs --since 1h --until 30m web
# write logs to a file
docker logs web > web.log 2>&1
# logs for all containers (compose)
docker compose logs -f
docker compose logs -f web db로그 드라이버
json-file 드라이버는 로테이션 없이는 무한히 커집니다 — 디스크 고갈을 막으려면 max-size와 max-file을 설정하세요. 프로덕션에서는 중앙 시스템(fluentd, splunk, awslogs, gelf)으로 로그를 보내세요. daemon.json에 전역 기본값을 두면 모든 컨테이너가 기본으로 로테이션됩니다.
# default: json-file
docker run -d --log-driver=json-file nginx
# cap log size and rotate (json-file)
docker run -d \
--log-driver=json-file \
--log-opt max-size=10m \
--log-opt max-file=3 \
nginx
# syslog
docker run -d --log-driver=syslog nginx
# journald
docker run -d --log-driver=journald nginx
# fluentd / splunk / gelf / awslogs
docker run -d --log-driver=fluentd nginx
# global default in /etc/docker/daemon.json
# { "log-driver": "json-file",
# "log-opts": { "max-size": "10m", "max-file": "3" } }로그 태깅 & 속성
tag 템플릿이 로그 식별자를 커스터마이징합니다 — {{.Name}}을 쓰면 잘린 ID 대신 읽기 쉬운 컨테이너 이름이 됩니다. fluentd/splunk에서는 labels와 환경 변수가 필터링을 위해 로그 레코드에 붙습니다. 모든 컨테이너가 일관되게 태깅되도록 데몬 수준 tag 템플릿을 설정하세요.
# tag logs with container name instead of ID
docker run -d \
--log-driver=json-file \
--log-opt tag="{{.Name}}" \
nginx
# tag with image name and tag
--log-opt tag="{{.ImageName}}/{{.Name}}"
# fluentd: add labels and attributes
docker run -d \
--log-driver=fluentd \
--log-opt fluentd-address=localhost:24224 \
--log-opt tag="docker.{{.Name}}" \
--log-opt labels=app,env \
--label app=web --label env=prod \
nginx
# syslog with facility
docker run -d --log-driver=syslog \
--log-opt syslog-facility=daemon nginx통계 & 리소스 모니터링
stats는 CPU, 메모리, 네트워크, 블록 IO를 스트리밍합니다. docker events는 데몬 이벤트의 실시간 스트림입니다 — 경보 스크립트에 유용합니다. docker top은 컨테이너 내부의 프로세스를, docker diff는 이미지 생성 이후의 파일시스템 변경(A=추가, C=변경, D=삭제)을 보여줍니다.
# live stats for all containers
docker stats
# specific container, one snapshot
docker stats --no-stream web
# custom format
docker stats --format "table {{.Name}} {{.CPUPerc}} {{.MemUsage}} {{.NetIO}}"
# events stream (start, stop, die, etc.)
docker events
# filter events
docker events --filter type=container --filter event=die
# container process list (like top)
docker top web
# container file changes since creation
docker diff webDocker 이벤트
docker events는 라이프사이클 이벤트의 실시간 스트림입니다: create, start, stop, pause, die, destroy, 그리고 이미지와 네트워크 이벤트. type, event, 컨테이너로 필터하세요. 컨테이너 사망에 반응하거나 실패한 서비스를 자동 재시작하는 경보 스크립트의 기초입니다.
# stream all events
docker events
# container events only
docker events --filter type=container
# specific event types
docker events --filter event=start --filter event=die
# events for a specific container
docker events --filter container=web
# events since a timestamp
docker events --since 1h
# format output
docker events --format '{{.Time}} {{.Action}} {{.Actor.Attributes.name}}'
# pipe to a monitoring script
docker events --filter event=die | while read event; do
echo "Container died: $event"
donePrometheus & Grafana 스택
cAdvisor는 컨테이너별 메트릭(CPU, 메모리, 네트워크, 파일시스템)을 Prometheus 형식으로 노출합니다. Prometheus가 긁어 저장하고, Grafana가 시각화합니다. Docker의 사실상 표준 오픈소스 모니터링 스택입니다. 호스트 메트릭에는 node-exporter를, 경보에는 alertmanager를 더하세요.
# run cAdvisor (container metrics exporter)
docker run -d --name cadvisor \
-v /:/rootfs:ro -v /var/run:/var/run:ro \
-v /sys:/sys:ro -v /var/lib/docker/:/var/lib/docker:ro \
-p 8080:8080 gcr.io/cadvisor/cadvisor
# run Prometheus
docker run -d -p 9090:9090 \
-v ./prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
# run Grafana
docker run -d -p 3000:3000 grafana/grafana
# scrape cAdvisor in prometheus.yml
# scrape_configs:
# - job_name: cadvisor
# static_configs:
# - targets: ['cadvisor:8080']
# view dashboards in Grafana at http://localhost:3000Docker Swarm
Swarm 초기화
swarm init은 Docker 호스트를 Swarm 매니저로 만듭니다. join 토큰으로 워커와 추가 매니저가 참여합니다. 매니저 토큰은 비밀로 유지하세요 — 클러스터를 제어할 수 있습니다. Raft 합의 내성을 위해 홀수 개의 매니저(3 또는 5)를 두세요. 워커가 태스크를 실행하고, 매니저가 스케줄합니다.
# initialize a Swarm (this node becomes a manager)
docker swarm init --advertise-addr 10.0.0.5
# get a join token for workers
docker swarm join-token worker
# get a join token for managers
docker swarm join-token manager
# on a worker node
docker swarm join --token SWMTKN-... 10.0.0.5:2377
# list nodes
docker node ls
# promote a worker to manager
docker node promote <node>
# demote a manager
docker node demote <node>
# leave the Swarm (worker)
docker swarm leave서비스 배포
서비스는 Swarm이 컨테이너를 추상화한 것입니다. replicated 서비스는 N개의 동일 태스크를 실행하고, global 서비스는 노드마다 하나의 태스크를 실행합니다. update는 기본적으로 무중단으로 새 이미지를 롤아웃합니다. scale이 복제본 수를 실시간으로 바꿉니다. 노드가 실패하면 Swarm이 재스케줄링합니다.
# deploy a service
docker service create --name web -p 80:80 nginx
# with replicas
docker service create --name web --replicas 3 -p 80:80 nginx
# with a constraint (e.g. only on worker nodes)
docker service create --name web --replicas 3 \
--constraint node.role==worker nginx
# with a global service (one per node)
docker service create --name log --mode global fluentd
# update the image
docker service update --image nginx:1.25 web
# scale a service
docker service scale web=5
# remove a service
docker service rm web스케일링 & 업데이트
scale은 복제본 수를 즉시 바꿉니다. update는 롤링 업데이트를 수행합니다 — parallelism이 한 번에 업데이트할 태스크 수를, delay가 간격을 정하고, failure-action=rollback이 오류 시 자동 되돌립니다. Swarm은 새 태스크가 건강해질 때까지 옛 태스크를 유지해 무중단 배포를 가능하게 합니다.
# scale up
docker service scale web=10
# scale multiple services
docker service scale web=5 worker=8
# rolling update
docker service update --image myapp:2.0 web
# update with parallelism and delay
docker service update \
--image myapp:2.0 \
--update-parallelism 2 \
--update-delay 30s \
--update-failure-action rollback \
web
# environment or port update without redeploy
docker service update --env-add DEBUG=true web
docker service update --publish-rm 80:80 --publish-add 8080:80 web
# rollback to previous version
docker service rollback web스택 배포
스택은 Swarm에 배포된 Compose 파일입니다. deploy: 키가 복제본, 업데이트/롤백 정책, 배치 제약, 리소스를 설정합니다 — 모두 Swarm 전용입니다. docker stack deploy가 스펙을 선언적으로 적용합니다. 스택은 관련 서비스, 네트워크, 시크릿을 그룹화합니다.
# docker-compose.yml as a Swarm stack
docker stack deploy -c docker-compose.yml mystack
# the compose file uses deploy: for Swarm config
services:
web:
image: nginx
deploy:
replicas: 3
update_config:
parallelism: 1
delay: 10s
restart_policy:
condition: on-failure
placement:
constraints: [node.role == worker]
ports:
- "80:80"
# list stacks and services
docker stack ls
docker stack services mystack
# remove a stack
docker stack rm mystack노드 관리
유지보수 전에 노드를 drain해 태스크를 다른 곳으로 우아하게 재스케줄하세요. active/pause/drain이 스케줄링을 제어합니다. 라벨은 배치 제약을 가능하게 합니다(예: tier=db 라벨 노드에서만 DB 실행). 노드 제거는 docker swarm leave로 Swarm을 떠난 뒤에만 하세요.
# list nodes
docker node ls
# node details (status, role, labels, resources)
docker node inspect <node>
# drain a node (reschedule tasks off it, for maintenance)
docker node update --availability drain <node>
# activate a drained node
docker node update --availability active <node>
# pause a node (no new tasks, existing stay)
docker node update --availability pause <node>
# add a label (for placement constraints)
docker node update --label-add tier=db <node>
# remove a node from the Swarm
docker node rm <node>
# (node must have left via 'docker swarm leave' first)시크릿 & 컨피그
시크릿은 저장 시와 전송 중 암호화되며, /run/secrets 아래 파일로 마운트되고, 이미지 레이어나 환경 변수에 절대 기록되지 않습니다. 불변입니다 — 교체하려면 새 시크릿을 만들고 서비스를 업데이트하세요. 컨피그는 비슷하지만 설정 파일 같은 민감하지 않은 데이터용입니다. 둘 다 Swarm 전용입니다.
# create a secret from a file
docker secret create db_password ./db_password.txt
# create from stdin
echo "supersecret" | docker secret create db_password -
# use in a service
docker service create --name app --secret db_password myapp
# read in the app
# cat /run/secrets/db_password
# update a secret (immutable — create a new one)
echo "newsecret" | docker secret create db_password_v2 -
docker service update --secret-rm db_password --secret-add source=db_password_v2 app
# configs (non-sensitive, e.g. nginx.conf)
echo "server {...}" | docker config create nginx_conf -
docker service create --config nginx_conf nginx
# list and remove
docker secret ls
docker config ls관련 Docker 스니펫
Copy-paste ready code for common tasks.
Run a Container
Run, list, stop, and remove Docker containers.
Writing a Dockerfile
Build an image from a Dockerfile with multi-instruction layers.
Image Management
Pull, list, tag, push, and prune images.
Volumes & Bind Mounts
Persist data with named volumes, anonymous volumes, and bind mounts.
Networking
Create networks, attach containers, and expose ports.
Docker Compose
Define and run multi-container apps with compose.
Multi-Stage Build
Build artifacts in one stage and copy them into a slim final image.
Exec & Logs
Run commands inside running containers and inspect logs.
Was this helpful?