Docker: Difference between revisions

From HPCWIKI
Jump to navigation Jump to search
No edit summary
(Phase 0.4: Expand Docker)
 
(8 intermediate revisions by 2 users not shown)
Line 1: Line 1:
== Docker container as user ==
= Docker =
Docker is a popular containerization tool. Docker containers are autonomous, lightweight, and portable, operating on any host system installed with Docker.


With Docker containers, users can isolate their applications from the fundamental host system and dependencies, rendering them more dependable and secure.
{{Status
|status=Draft
|owner=Knowledge Agent
|last_update=2026-07-15
|review=Pending
}}


== Set user in container ==
{{TOC}}
'''By default, Docker runs containers with a root user, which can create a security risk and cause permission issues when accessing files and directories.'''


'''It is good idea to make the container user should be a non-root user with appropriate permissions.'''
== Overview ==


=== Using the ''--user'' option of ''docker run'' command ===
Docker는 컨테이너 기반의 가상화 플랫폼으로, 애플리케이션을 독립된 환경에 패키징하여 어디서든 일관되게 실행할 수 있게 합니다.
Docker offers --user option to set the UID and GID of the user inside the container while it is running.


Following command will run ubuntu image with current user who execute this command  <syntaxhighlight lang="bash">
=== Summary ===
$docker run -it --rm -v /home/$USER:/home/$USER -w /home/$USER -u $(id -u):$(id -g) ubuntu
</syntaxhighlight>where,


-w means container working directory
* 무엇인가? — 컨테이너 기반 애플리케이션 가상화 플랫폼
* 왜 필요한가? — 환경 일관성, 빠른 배포, 리소스 효율성
* 언제 사용하는가? — 개발/테스트/운영 환경, 마이크로서비스, CI/CD


-u host system user UID and GID 


To extend this capability, following example enables execute user to login of their container using host UID/GID, if we setup ssh server inside of container. <syntaxhighlight lang="bash">
== Purpose ==
$ docker run --rm
    -u $(id -u):$(id -g)                    #set the user’s UID and GID in the container.
    -w /home/$USER                          #sets the working directory to the user’s home
    -v /home/$USER:/home/$USER              #volume mount to container home
    -v /etc/group:/etc/group:ro            #for container authentification
    -v /etc/passwd:/etc/passwd:ro
    -v /etc/shadow:/etc/shadow:ro
    ubuntu bash -c "whoami; pwd"


이 문서가 존재하는 이유
* Goal: Docker 기본 개념부터 실전 명령어, 리소스 관리까지 한 곳에서 제공
* Scope: Docker 기본 명령어, 컨테이너 리소스 제한, Dockerfile, 이미지 관리
* Non-goals: Kubernetes 오케스트레이션, Docker Compose 고급 설정은 별도 문서
== Key Concepts ==
{| class="wikitable"
! Concept
! Description
! Related
|-
| Container
| 독립된 실행 환경 (OS 레벨 가상화)
| [[Docker]]
|-
| Image
| 컨테이너 생성을 위한 템플릿
| [[Docker command workflow]]
|-
| Dockerfile
| 이미지 빌드 설정 파일
| [[Docker command workflow]]
|-
| Volume
| 컨테이너 외부 저장소 마운트
| [[Docker library sharing]]
|-
| Resource Limit
| CPU/메모리/디스크 사용량 제한
| [[Docker container resource]]
|}
== Architecture ==
Docker는 클라이언트-서버 아키텍처로 구성됩니다:
<syntaxhighlight lang="mermaid">
graph TD
    A[Docker Client] --> B[Docker Daemon]
    B --> C[Container Runtime]
    B --> D[Image Store]
    B --> E[Network Manager]
    B --> F[Volume Manager]
    C --> G[Container 1]
    C --> H[Container 2]
    C --> I[Container N]
</syntaxhighlight>
</syntaxhighlight>


=== Set User in Dockerfile ===
With custom Dockerfile, we can create new docker images by defining a specific user in container. <syntaxhighlight lang="dockerfile">
FROM Ubuntu:latest                                      #base image
ARG _USER=default_user                                  #ARG for container user
RUN addgroup -S $_USER && adduser -S $_USER -G $_USER  #Create container user/group
USER $_USER                                            #set container user
CMD ["whoami"]
</syntaxhighlight>Then craete Docker image


<code>$ docker build --build-arg _USER=username -t dynamicuser .</code>
== Workflow ==


Verify user inside of container will show the username
{| class="wikitable"
! Stage
! Input
! Output
|-
| Build
| Dockerfile
| Docker Image
|-
| Run
| Docker Image
| Running Container
|-
| Push
| Docker Image
| Registry Upload
|-
| Pull
| Registry
| Docker Image Download
|}


<code>$ docker run --rm  --name dynamicuser dynamicuser</code>


== [https://docs.docker.com/engine/security/rootless/ Rootless mode] ==
== Detailed Explanation ==
Docker Engine v19.03 introduced Rootless mode and included  Docker Engine v20.10 or later.


Rootless mode allows running the Docker daemon and containers as a non-root user to mitigate potential vulnerabilities in the daemon and the container runtime. Rootless mode does not require root privileges even during the installation of the Docker daemon, as long as the special prerequisites<ref>https://docs.docker.com/engine/security/rootless/#prerequisites</ref> are met.
=== Docker 기본 ===


== Reference ==
Docker는 [[Linux]] 컨테이너(LXC)를 기반으로 합니다. 호스트 커널을 공유하면서 격리된 환경을 제공합니다.
 
=== Docker 명령어 워크플로우 ===
 
Dockerfile 작성 → 이미지 빌드 → 컨테이너 실행 → 레지스트리 푸시 → 다른 시스템에서 풀/실행
 
=== Docker 컨테이너 리소스 ===
 
컨테이너는 기본적으로 CPU, 메모리, 디스크 사용량이 제한됩니다. --memory, --cpus 옵션으로 제한을 설정할 수 있습니다.
 
=== Docker 라이브러리 공유 ===
 
볼륨(Volume)과 바인드 마운트를 통해 호스트와 컨테이너 간 파일을 공유합니다.
 
 
== Configuration ==
 
<syntaxhighlight lang="bash">
# Docker 버전 확인
docker --version
 
# 이미지 빌드
docker build -t myapp:latest .
 
# 컨테이너 실행
docker run -d --name myapp --memory=2g --cpus=2 myapp:latest
 
# 컨테이너 리소스 제한
docker run -d --memory=4g --memory-swap=4g --cpus=4 myapp:latest
 
# 로그 확인
docker logs -f myapp
 
# 컨테이너 상태 확인
docker ps -a
docker stats
</syntaxhighlight>
 
 
== Examples ==
 
=== Example 1: Dockerfile 작성 ===
 
<syntaxhighlight lang="dockerfile">
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]
</syntaxhighlight>
 
=== Example 2: 리소스 제한 컨테이너 실행 ===
 
<syntaxhighlight lang="bash">
docker run -d  --name gpu-container  --gpus all  --memory=8g  --cpus=4  --restart=unless-stopped  myapp:latest
</syntaxhighlight>
 
 
== Best Practices ==
 
* 다단계 빌드(Docker multi-stage build) 활용
* .dockerignore 파일 작성
* 공식 이미지 기반 시작
* 불변 태그(immutable tag) 사용
* 컨테이너 로그 관리 설정
* 리소스 제한 필수 적용
 
 
== Limitations ==
 
* Linux 호스트 필요 (Windows/macOS는 VM 오버헤드)
* 커널 기능 의존 (cgroups, namespaces)
* 보안 격리는 호스트 커널 공유로 제한적
 
 
== References ==
 
* https://docs.docker.com/
* https://hub.docker.com/
* https://github.com/docker
 
 
== Related Pages ==
 
* [[Docker command workflow]]
* [[Docker container resource]]
* [[Container tips and tricks]]
* [[Dockerfile tips and tricks]]
* [[Kubernetes]]
 
 
[[Category:Network]]
== Knowledge Graph ==
 
Related
 
→ [[Kubernetes]]
→ [[Container]]
→ [[Dockerfile]]
→ [[Docker Compose]]
 
[[Category:Guide]]
 
== GPU Docker ==
 
Docker에서 GPU 사용하려면 NVIDIA Container Toolkit 필요.
 
<syntaxhighlight lang="bash">
# NVIDIA Container Toolkit 설치
curl -s -L https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo | \
  sudo tee /etc/yum.repos.d/nvidia-container-toolkit.repo
 
sudo yum install -y nvidia-container-toolkit
sudo systemctl restart docker
 
# GPU 컨테이너 실행
docker run --gpus all nvidia/cuda:12.2-base nvidia-smi
 
# 특정 GPU만 사용
docker run --gpus 'device=0,1' nvidia/cuda:12.2-base nvidia-smi
 
# GPU 메모리 제한
docker run --gpus 'device=0,reserved-memory=4096' nvidia/cuda:12.2-base
</syntaxhighlight>
 
== Docker Compose ==
 
Docker Compose는 멀티 컨테이너 애플리케이션 관리.
 
<syntaxhighlight lang="yaml">
version: '3.8'
services:
  app:
    image: myapp:latest
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
    ports:
      - "8080:8080"
    volumes:
      - ./data:/app/data
    restart: unless-stopped
 
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
 
volumes:
  redis-data:
</syntaxhighlight>
 
<syntaxhighlight lang="bash">
# Compose 실행
docker compose up -d
 
# 로그 확인
docker compose logs -f app
 
# 서비스 재시작
docker compose restart app
</syntaxhighlight>
 
== Docker Swarm ==
 
Docker Swarm은 Docker 네이티브 오케스트레이션.
 
<syntaxhighlight lang="bash">
# Swarm 초기화
docker swarm init --advertise-addr eth0
 
# 서비스 배포
docker service create --name myapp --replicas 3 -p 8080:80 myapp:latest
 
# 서비스 상태 확인
docker service ls
docker service ps myapp
 
# 스케일링
docker service scale myapp=5
</syntaxhighlight>

Latest revision as of 13:37, 17 July 2026

Docker

Template:Status

Template:TOC

Overview

Docker는 컨테이너 기반의 가상화 플랫폼으로, 애플리케이션을 독립된 환경에 패키징하여 어디서든 일관되게 실행할 수 있게 합니다.

Summary

  • 무엇인가? — 컨테이너 기반 애플리케이션 가상화 플랫폼
  • 왜 필요한가? — 환경 일관성, 빠른 배포, 리소스 효율성
  • 언제 사용하는가? — 개발/테스트/운영 환경, 마이크로서비스, CI/CD


Purpose

이 문서가 존재하는 이유

  • Goal: Docker 기본 개념부터 실전 명령어, 리소스 관리까지 한 곳에서 제공
  • Scope: Docker 기본 명령어, 컨테이너 리소스 제한, Dockerfile, 이미지 관리
  • Non-goals: Kubernetes 오케스트레이션, Docker Compose 고급 설정은 별도 문서


Key Concepts

Concept Description Related
Container 독립된 실행 환경 (OS 레벨 가상화) Docker
Image 컨테이너 생성을 위한 템플릿 Docker command workflow
Dockerfile 이미지 빌드 설정 파일 Docker command workflow
Volume 컨테이너 외부 저장소 마운트 Docker library sharing
Resource Limit CPU/메모리/디스크 사용량 제한 Docker container resource


Architecture

Docker는 클라이언트-서버 아키텍처로 구성됩니다:

graph TD
    A[Docker Client] --> B[Docker Daemon]
    B --> C[Container Runtime]
    B --> D[Image Store]
    B --> E[Network Manager]
    B --> F[Volume Manager]
    C --> G[Container 1]
    C --> H[Container 2]
    C --> I[Container N]


Workflow

Stage Input Output
Build Dockerfile Docker Image
Run Docker Image Running Container
Push Docker Image Registry Upload
Pull Registry Docker Image Download


Detailed Explanation

Docker 기본

Docker는 Linux 컨테이너(LXC)를 기반으로 합니다. 호스트 커널을 공유하면서 격리된 환경을 제공합니다.

Docker 명령어 워크플로우

Dockerfile 작성 → 이미지 빌드 → 컨테이너 실행 → 레지스트리 푸시 → 다른 시스템에서 풀/실행

Docker 컨테이너 리소스

컨테이너는 기본적으로 CPU, 메모리, 디스크 사용량이 제한됩니다. --memory, --cpus 옵션으로 제한을 설정할 수 있습니다.

Docker 라이브러리 공유

볼륨(Volume)과 바인드 마운트를 통해 호스트와 컨테이너 간 파일을 공유합니다.


Configuration

# Docker 버전 확인
docker --version

# 이미지 빌드
docker build -t myapp:latest .

# 컨테이너 실행
docker run -d --name myapp --memory=2g --cpus=2 myapp:latest

# 컨테이너 리소스 제한
docker run -d --memory=4g --memory-swap=4g --cpus=4 myapp:latest

# 로그 확인
docker logs -f myapp

# 컨테이너 상태 확인
docker ps -a
docker stats


Examples

Example 1: Dockerfile 작성

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]

Example 2: 리소스 제한 컨테이너 실행

docker run -d   --name gpu-container   --gpus all   --memory=8g   --cpus=4   --restart=unless-stopped   myapp:latest


Best Practices

  • 다단계 빌드(Docker multi-stage build) 활용
  • .dockerignore 파일 작성
  • 공식 이미지 기반 시작
  • 불변 태그(immutable tag) 사용
  • 컨테이너 로그 관리 설정
  • 리소스 제한 필수 적용


Limitations

  • Linux 호스트 필요 (Windows/macOS는 VM 오버헤드)
  • 커널 기능 의존 (cgroups, namespaces)
  • 보안 격리는 호스트 커널 공유로 제한적


References


Related Pages

Knowledge Graph

Related

KubernetesContainerDockerfileDocker Compose

GPU Docker

Docker에서 GPU 사용하려면 NVIDIA Container Toolkit 필요.

# NVIDIA Container Toolkit 설치
curl -s -L https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo | \
  sudo tee /etc/yum.repos.d/nvidia-container-toolkit.repo

sudo yum install -y nvidia-container-toolkit
sudo systemctl restart docker

# GPU 컨테이너 실행
docker run --gpus all nvidia/cuda:12.2-base nvidia-smi

# 특정 GPU만 사용
docker run --gpus 'device=0,1' nvidia/cuda:12.2-base nvidia-smi

# GPU 메모리 제한
docker run --gpus 'device=0,reserved-memory=4096' nvidia/cuda:12.2-base

Docker Compose

Docker Compose는 멀티 컨테이너 애플리케이션 관리.

version: '3.8'
services:
  app:
    image: myapp:latest
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
    ports:
      - "8080:8080"
    volumes:
      - ./data:/app/data
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data

volumes:
  redis-data:
# Compose 실행
docker compose up -d

# 로그 확인
docker compose logs -f app

# 서비스 재시작
docker compose restart app

Docker Swarm

Docker Swarm은 Docker 네이티브 오케스트레이션.

# Swarm 초기화
docker swarm init --advertise-addr eth0

# 서비스 배포
docker service create --name myapp --replicas 3 -p 8080:80 myapp:latest

# 서비스 상태 확인
docker service ls
docker service ps myapp

# 스케일링
docker service scale myapp=5