Docker Compose 备忘单

Docker Compose 格式备忘单

Docker Compose is a powerful tool for defining and running multi-container Docker applications. It uses a YAML file (compose.yaml) to configure application services, networks, volumes, and more. This file allows developers to declaratively describe infrastructure and dependencies, making it easier to manage complex environments.

Whether you’re building a local dev stack or deploying to production, Compose simplifies orchestration and keeps your configuration readable and version-controlled.

📁 File Name

compose.yaml 

✅ YAML Formatting Rules

  • Use 2 spaces for indentation (not tabs)
  • Keys and values are case-sensitive
  • Lists use - for each item
  • Strings with special characters should be quoted
  • Environment variables can be defined inline or via .env files

🧱 Basic Structure

services: service_name: image: image_name:tag build: context: . dockerfile: Dockerfile ports: - "host_port:container_port" volumes: - ./host_path:/container_path environment: - VAR_NAME=value depends_on: - other_service networks: - custom_network networks: custom_network: driver: bridge volumes: custom_volume: 

⚙️ Services

Each service defines a container.

Common Service Options

services: web: image: nginx:latest build: context: ./app dockerfile: Dockerfile command: ["nginx", "-g", "daemon off;"] container_name: custom_name ports: - "8080:80" expose: - "80" environment: - DEBUG=true env_file: - .env volumes: - ./data:/data restart: always depends_on: - db networks: - frontend healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 30s timeout: 10s retries: 5 

🏗️ Build Options

build: context: ./dir dockerfile: Dockerfile args: build_arg: value target: build-stage 
  • build: Tells Compose how to build the image.
    • context: is the directory containing the Dockerfile and source code.
    • dockerfile: lets you specify a custom Dockerfile name or path.

📦 Volumes

volumes: data_volume: driver: local driver_opts: type: none device: /path/on/host o: bind 

Mounting Volumes

volumes: - data_volume:/app/data - ./local:/container/path 
  • volumes: Mounts host directories or named volumes into the container.
    • ./src:/app/src mounts the local src folder into the container at /app/src.

🌐 Networks

networks: frontend: driver: bridge backend: driver: overlay 
  • networks: Connects the service to one or more custom networks. Enables service discovery and isolation.

Assigning Networks to Services

services: app: networks: - frontend - backend 

🌐 Ports

 ports: - "3000:3000" 
  • ports: Maps container ports to host ports. Format is "host:container". Useful for exposing services to your local machine.

🔐 Secrets (Docker Swarm only)

secrets: db_password: file: ./db_password.txt services: db: secrets: - db_password 

🔑 Configs (Docker Swarm only)

configs: my_config: file: ./config.txt services: app: configs: - source: my_config target: /etc/config.txt 

🧪 Healthcheck

healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 30s timeout: 10s retries: 3 start_period: 5s 
  • healthcheck: Defines how Docker checks if the container is healthy.
    • test: is the command to run
    • interval: how often to run the check
    • timeout: how long to wait for a response
    • retries: how many failures before marking unhealthy

🔄 Restart Policies

restart: no # Never restart restart: always # Always restart restart: on-failure # Restart on failure restart: unless-stopped 

🧬 Environment Variables

environment: - VAR1=value1 - VAR2=value2 env_file: - .env 
  • environment: Sets environment variables inside the container. Useful for configuration.
  • env_file: Loads environment variables from a file. Keeps secrets and config separate from the Compose file.

Command

 command: npm start 
  • command: Overrides the default command defined in the Dockerfile. Useful for customizing container behavior.

Dependencies

 depends_on: - db 
  • depends_on: Specifies service startup order. In Compose, this does not wait for the service to be “ready”—just started.

🧹 Clean Up

docker compose down # Stop and remove containers, networks, volumes docker compose down -v # Also remove named volumes 

🚀 Commands

CommandDescription
docker compose upStart services
docker compose up -dStart in detached mode
docker compose downStop and remove services
docker compose buildBuild images
docker compose psList containers
docker compose logsView logs
docker compose exec <service> <cmd>Run command in container
docker compose configValidate and view config

🧠 Mounting GPU / iGPU

Docker Compose supports GPU access via the device_requests field (Compose v3.8+ and Docker 19.03+).

✅ NVIDIA GPU Example

services: gpu-app: image: nvidia/cuda:11.0-base deploy: resources: reservations: devices: - driver: nvidia count: all capabilities: [gpu] 

✅ Intel iGPU (via VAAPI or OpenCL)

services: igpu-app: image: intel/openvino devices: - /dev/dri:/dev/dri 

🔧 Make sure your host has the necessary drivers and runtime (e.g., NVIDIA Container Toolkit or Intel Media SDK).

🔄 Compose vs Swarm YAML Differences

FeatureDocker Compose (compose.yaml)Docker Swarm (stack.yml)
restart✅ Supported❌ Not supported
depends_on✅ Supported❌ Not supported
deploy❌ Ignored✅ Required for replicas
build✅ Supported❌ Not supported
volumes (bind)✅ Supported✅ Supported
configs/secrets❌ Ignored✅ Supported
healthcheck✅ Supported✅ Supported

🧠 Tip: Use compose.yaml for local development and stack.yml for Swarm deployments.

🧬 Profiles (Compose v3.9+)

Profiles allow conditional inclusion of services based on the active profile. This is useful for separating dev/test/staging environments.

✅ Defining Profiles

services: web: image: nginx profiles: - default debug: image: busybox command: top profiles: - debug 

✅ Activating Profiles

docker compose --profile debug up 

✅ Notes

  • Services without a profiles key are always included.
  • Multiple profiles can be activated simultaneously.
  • Useful for feature toggles, optional services, or environment-specific setups.

⚔️ YAML Differences: Docker Compose vs Docker Swarm Mode

Docker Compose and Docker Swarm both use YAML files to define services, but they serve different purposes and support different features. Compose is optimized for local development and testing, while Swarm is designed for production-grade orchestration across clusters.

🧭 Purpose

ModeUse Case
ComposeLocal development, testing
SwarmCluster deployment, scaling

🧩 Key Differences in YAML Structure

FeatureCompose (compose.yaml)Swarm (stack.yml)
build:✅ Supported❌ Ignored
restart:✅ Supported❌ Ignored
depends_on:✅ Supported❌ Ignored
deploy:❌ Ignored✅ Required for scaling, placement
configs:❌ Ignored✅ Supported
secrets:❌ Ignored✅ Supported
healthcheck:✅ Supported✅ Supported
volumes: (bind)✅ Supported✅ Supported
networks:✅ Supported✅ Supported
profiles:✅ Supported (v3.9+)❌ Not supported

🔧 Compose-Only Features

These features are useful for local development but are ignored in Swarm:

build:

services: app: build: context: . dockerfile: Dockerfile 
  • Compose builds images locally.
  • Swarm requires pre-built images pushed to a registry.

restart:

restart: unless-stopped 
  • Compose uses this to auto-restart containers.
  • Swarm uses deploy.restart_policy instead.

depends_on:

depends_on: - db 
  • Compose starts services in order.
  • Swarm ignores this; use healthchecks and wait-for-it scripts.

🛡️ Swarm-Only Features

These features are exclusive to Swarm and ignored by Compose:

deploy:

services: app: deploy: replicas: 3 placement: constraints: - node.role == manager restart_policy: condition: on-failure 
  • Controls scaling, placement, and restart behavior in a cluster.

configs: and secrets:

configs: app_config: file: ./config.yml secrets: db_password: file: ./password.txt 
  • Used to securely distribute configuration and secrets across nodes.

placement: (inside deploy)

placement: constraints: - node.labels.env == production 
  • Assigns services to specific nodes based on labels.

🧪 Healthchecks (Supported in Both)

healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 30s timeout: 10s retries: 3 
  • Works in both Compose and Swarm.
  • In Swarm, health status can influence service rescheduling.

📦 Volume Differences

TypeComposeSwarm
Bind mount
Named volume
External volume
Volume driver options

Swarm requires external volumes to be pre-created on all nodes.

🧠 Summary

Feature CategoryComposeSwarm
Local builds
Cluster scaling
Secrets/configs
Profiles
Restart policies✅ (via deploy)
Service dependencies

🧭 Tip: Use compose.yaml for development and stack.yml for Swarm. You can split your configuration into multiple files or use tools like kompose to convert Kubernetes manifests.

📚 Resources

相关工具 (20)

chmod 命令速查表
Linux 权限变更速查表
常用正则表达式备忘单
常用正则表达式模式备忘单。
CSS选择器备忘单
CSS选择器语法备忘单。
Docker Compose 备忘单
Docker Compose 格式备忘单
Docker备忘单
Docker命令备忘单。
Docker SWARM 备忘单
Docker Swarm 模式速查表
Dockerfile 备忘单
Dockerfile 语法和构建备忘单
Git语义提交备忘单
使用语义前缀提交Git的备忘单
JQ备忘单
JQ命令备忘单
JSONPath语法备忘单
JSONPath语法备忘单
Markdown备忘单
Markdown备忘单
Nano备忘单
Nano编辑器备忘单
正则表达式备忘单
JavaScript正则表达式备忘单
Sed 备忘单
sed unix 命令速查表
XPath语法备忘单
XPath语法备忘单
ZPool 备忘单
OpenZFS/ZPool 使用命令和信息
Docker Compose格式转换器
在V1、2.x、3.x或CommonSpec之间转换Docker Compose文件,可扩展端口/卷语法。
Docker Compose到Docker运行转换器
将Docker Compose文件转换为docker run命令!
Docker Compose 到 .env 文件
从现有的 Docker Compose 文件中提取 .env 文件
Docker Compose到Kubernetes
Docker Compose转换为Kubernetes清单。
留言区
昵称
邮箱
网址
0/1000
0 条评论
没有评论
Powered by Twikoo v1.6.44
Twikoo 评论管理
密码