docker-platform-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

🚨 CRITICAL GUIDELINES

⚠️ 关键准则

Windows File Path Requirements

Windows文件路径要求

MANDATORY: Always Use Backslashes on Windows for File Paths
When using Edit or Write tools on Windows, you MUST use backslashes (
\
) in file paths, NOT forward slashes (
/
).
Examples:
  • ❌ WRONG:
    D:/repos/project/file.tsx
  • ✅ CORRECT:
    D:\repos\project\file.tsx
This applies to:
  • Edit tool file_path parameter
  • Write tool file_path parameter
  • All file operations on Windows systems
强制要求:在Windows系统中始终使用反斜杠表示文件路径
在Windows系统上使用编辑或写入工具时,文件路径必须使用反斜杠(
\
),而不能使用正斜杠(
/
)。
示例:
  • ❌ 错误写法:
    D:/repos/project/file.tsx
  • ✅ 正确写法:
    D:\repos\project\file.tsx
此要求适用于:
  • 编辑工具的file_path参数
  • 写入工具的file_path参数
  • Windows系统上的所有文件操作

Documentation Guidelines

文档编写准则

NEVER create new documentation files unless explicitly requested by the user.
  • Priority: Update existing README.md files rather than creating new documentation
  • Repository cleanliness: Keep repository root clean - only README.md unless user requests otherwise
  • Style: Documentation should be concise, direct, and professional - avoid AI-generated tone
  • User preference: Only create additional .md files when user specifically asks for documentation

除非用户明确要求,否则绝不创建新的文档文件。
  • 优先级:优先更新现有的README.md文件,而非创建新文档
  • 仓库整洁性:保持仓库根目录整洁 - 除非用户要求,否则仅保留README.md
  • 风格:文档应简洁、直接且专业 - 避免AI生成的冗余语气
  • 用户偏好:仅当用户明确要求时,才创建额外的.md文件

Docker Platform-Specific Guide

Docker平台专属指南

This skill provides detailed guidance on Docker differences, considerations, and optimizations for Windows, Linux, and macOS platforms.
本指南详细介绍了Docker在Windows、Linux和macOS平台上的差异、注意事项及优化方案。

Linux

Linux

Advantages

优势

  • Native containers: No virtualization layer overhead
  • Best performance: Direct kernel features (cgroups, namespaces)
  • Full feature set: All Docker features available
  • Production standard: Most production deployments run on Linux
  • Flexibility: Multiple distributions supported
  • 原生容器:无虚拟化层开销
  • 最佳性能:直接使用内核特性(cgroups、namespaces)
  • 完整功能集:支持所有Docker功能
  • 生产标准:绝大多数生产部署基于Linux
  • 灵活性:支持多种发行版

Platform Features

平台特性

Container Technologies:
  • Namespaces: PID, network, IPC, mount, UTS, user
  • cgroups v1 and v2 for resource control
  • Overlay2 storage driver (recommended)
  • SELinux and AppArmor for mandatory access control
Storage Drivers:
bash
undefined
容器技术:
  • Namespaces:PID、网络、IPC、挂载、UTS、用户
  • cgroups v1和v2用于资源控制
  • Overlay2存储驱动(推荐)
  • SELinux和AppArmor用于强制访问控制
存储驱动:
bash
undefined

Check current driver

检查当前驱动

docker info | grep "Storage Driver"
docker info | grep "Storage Driver"

Recommended: overlay2

推荐使用:overlay2

/etc/docker/daemon.json

/etc/docker/daemon.json

{ "storage-driver": "overlay2" }
undefined
{ "storage-driver": "overlay2" }
undefined

Linux-Specific Configuration

Linux专属配置

Daemon Configuration (
/etc/docker/daemon.json
):
json
{
  "storage-driver": "overlay2",
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "live-restore": true,
  "userland-proxy": false,
  "userns-remap": "default",
  "icc": false,
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 64000,
      "Soft": 64000
    }
  }
}
User Namespace Remapping:
bash
undefined
守护进程配置
/etc/docker/daemon.json
):
json
{
  "storage-driver": "overlay2",
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "live-restore": true,
  "userland-proxy": false,
  "userns-remap": "default",
  "icc": false,
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 64000,
      "Soft": 64000
    }
  }
}
用户命名空间映射:
bash
undefined

Enable in daemon.json

在daemon.json中启用

{ "userns-remap": "default" }
{ "userns-remap": "default" }

Restart Docker

重启Docker

sudo systemctl restart docker
sudo systemctl restart docker

Result: root in container = unprivileged user on host

效果:容器内的root用户对应主机上的非特权用户

undefined
undefined

SELinux Integration

SELinux集成

bash
undefined
bash
undefined

Check SELinux status

检查SELinux状态

sestatus
sestatus

Run container with SELinux enabled

运行启用SELinux的容器

docker run --security-opt label=type:svirt_sandbox_file_t myimage
docker run --security-opt label=type:svirt_sandbox_file_t myimage

Volume labels

卷标签

docker run -v /host/path:/container/path:z myimage # Private label docker run -v /host/path:/container/path:Z myimage # Shared label
undefined
docker run -v /host/path:/container/path:z myimage # 私有标签 docker run -v /host/path:/container/path:Z myimage # 共享标签
undefined

AppArmor Integration

AppArmor集成

bash
undefined
bash
undefined

Check AppArmor status

检查AppArmor状态

sudo aa-status
sudo aa-status

Run with default Docker profile

使用默认Docker配置文件运行容器

docker run --security-opt apparmor=docker-default myimage
docker run --security-opt apparmor=docker-default myimage

Create custom profile

创建自定义配置文件

sudo aa-genprof docker run myimage
undefined
sudo aa-genprof docker run myimage
undefined

Systemd Integration

Systemd集成

bash
undefined
bash
undefined

Check Docker service status

检查Docker服务状态

sudo systemctl status docker
sudo systemctl status docker

Enable on boot

设置开机自启

sudo systemctl enable docker
sudo systemctl enable docker

Restart Docker

重启Docker

sudo systemctl restart docker
sudo systemctl restart docker

View logs

查看日志

sudo journalctl -u docker -f
sudo journalctl -u docker -f

Configure service

配置服务

sudo systemctl edit docker
undefined
sudo systemctl edit docker
undefined

cgroup v1 vs v2

cgroup v1 vs v2

bash
undefined
bash
undefined

Check cgroup version

检查cgroup版本

stat -fc %T /sys/fs/cgroup/
stat -fc %T /sys/fs/cgroup/

If using cgroup v2, ensure Docker version >= 20.10

如果使用cgroup v2,确保Docker版本 >= 20.10

/etc/docker/daemon.json

/etc/docker/daemon.json

{ "exec-opts": ["native.cgroupdriver=systemd"] }
undefined
{ "exec-opts": ["native.cgroupdriver=systemd"] }
undefined

Linux Distribution Specifics

Linux发行版专属说明

Ubuntu/Debian:
bash
undefined
Ubuntu/Debian:
bash
undefined

Install Docker

安装Docker

sudo apt-get update sudo apt-get install ca-certificates curl sudo install -m 0755 -d /etc/apt/keyrings sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc sudo chmod a+r /etc/apt/keyrings/docker.asc
echo
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" |
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io
sudo apt-get update sudo apt-get install ca-certificates curl sudo install -m 0755 -d /etc/apt/keyrings sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc sudo chmod a+r /etc/apt/keyrings/docker.asc
echo
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" |
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io

Non-root user

配置非root用户

sudo usermod -aG docker $USER

**RHEL/CentOS/Fedora:**
```bash
sudo usermod -aG docker $USER

**RHEL/CentOS/Fedora:**
```bash

Install Docker

安装Docker

sudo dnf -y install dnf-plugins-core sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io
sudo dnf -y install dnf-plugins-core sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io

Start Docker

启动Docker

sudo systemctl start docker sudo systemctl enable docker
sudo systemctl start docker sudo systemctl enable docker

Non-root user

配置非root用户

sudo usermod -aG docker $USER

**Alpine:**
```bash
sudo usermod -aG docker $USER

**Alpine:**
```bash

Install Docker

安装Docker

apk add docker docker-compose
apk add docker docker-compose

Start Docker

启动Docker

rc-update add docker boot service docker start
undefined
rc-update add docker boot service docker start
undefined

macOS

macOS

Architecture

架构

  • Docker Desktop: Required (no native Docker on macOS)
  • Virtualization: Uses HyperKit (Intel) or Virtualization.framework (Apple Silicon)
  • Linux VM: Containers run in lightweight Linux VM
  • File sharing: osxfs or VirtioFS for bind mounts
  • Docker Desktop:必须安装(macOS无原生Docker)
  • 虚拟化:使用HyperKit(Intel芯片)或Virtualization.framework(Apple Silicon芯片)
  • Linux虚拟机:容器运行在轻量级Linux虚拟机中
  • 文件共享:使用osxfs或VirtioFS进行绑定挂载

macOS-Specific Considerations

macOS专属注意事项

Resource Allocation:
Docker Desktop → Preferences → Resources → Advanced
- CPUs: Allocate based on workload (default: half available)
- Memory: Allocate generously (default: 2GB, recommend 4-8GB)
- Swap: 1GB minimum
- Disk image size: 60GB+ for development
File Sharing Performance:
Traditional osxfs is slow. Improvements:
  1. VirtioFS: Enable in Docker Desktop settings (faster)
  2. Delegated/Cached mounts:
yaml
volumes:
  # Host writes delayed (best for source code)
  - ./src:/app/src:delegated

  # Container writes cached (best for build outputs)
  - ./build:/app/build:cached

  # Default consistency (slowest but safest)
  - ./data:/app/data:consistent
Network Access:
bash
undefined
资源分配:
Docker Desktop → 偏好设置 → 资源 → 高级
- CPU:根据工作负载分配(默认:可用CPU的一半)
- 内存:充足分配(默认:2GB,推荐4-8GB)
- 交换空间:最小1GB
- 磁盘镜像大小:开发环境建议60GB以上
文件共享性能:
传统osxfs速度较慢,可通过以下方式优化:
  1. VirtioFS:在Docker Desktop设置中启用(速度更快)
  2. 委托/缓存挂载:
yaml
volumes:
  # 主机写入延迟(适用于源代码)
  - ./src:/app/src:delegated

  # 容器写入缓存(适用于构建输出)
  - ./build:/app/build:cached

  # 默认一致性(最慢但最安全)
  - ./data:/app/data:consistent
网络访问:
bash
undefined

Access host from container

从容器访问主机

host.docker.internal
host.docker.internal

Example: Connect to host PostgreSQL

示例:连接主机上的PostgreSQL

docker run -e DATABASE_URL=postgresql://host.docker.internal:5432/db myapp
undefined
docker run -e DATABASE_URL=postgresql://host.docker.internal:5432/db myapp
undefined

Apple Silicon (M1/M2/M3) Specifics

Apple Silicon(M1/M2/M3)专属说明

Architecture Considerations:
bash
undefined
架构注意事项:
bash
undefined

Check image architecture

检查镜像架构

docker image inspect node:20-alpine | grep Architecture
docker image inspect node:20-alpine | grep Architecture

M-series Macs are ARM64

M系列Mac为ARM64架构

Some images only available for AMD64

部分镜像仅支持AMD64

Build multi-platform

构建多平台镜像

docker buildx build --platform linux/amd64,linux/arm64 -t myapp .
docker buildx build --platform linux/amd64,linux/arm64 -t myapp .

Run AMD64 image on ARM (via emulation)

在ARM架构上运行AMD64镜像(通过模拟)

docker run --platform linux/amd64 myimage # Slower

**Rosetta 2 Integration:**
Docker Desktop → Features in development → Use Rosetta for x86/amd64 emulation
Faster AMD64 emulation on Apple Silicon.
docker run --platform linux/amd64 myimage # 速度较慢

**Rosetta 2集成:**
Docker Desktop → 开发中功能 → 使用Rosetta进行x86/amd64模拟
可提升Apple Silicon上AMD64镜像的模拟速度。

macOS Docker Desktop Settings

macOS Docker Desktop设置

General:
  • ✅ Start Docker Desktop when you log in
  • ✅ Use VirtioFS (better performance)
  • ✅ Use Virtualization framework (Apple Silicon)
Resources:
CPUs: 4-6 (for development)
Memory: 6-8 GB (for development)
Swap: 1-2 GB
Disk image size: 100+ GB (grows dynamically)
Docker Engine:
json
{
  "builder": {
    "gc": {
      "enabled": true,
      "defaultKeepStorage": "20GB"
    }
  },
  "experimental": false,
  "features": {
    "buildkit": true
  }
}
常规:
  • ✅ 登录时启动Docker Desktop
  • ✅ 使用VirtioFS(性能更佳)
  • ✅ 使用Virtualization.framework(Apple Silicon)
资源:
CPU:4-6核(开发环境)
内存:6-8GB(开发环境)
交换空间:1-2GB
磁盘镜像大小:100GB以上(动态增长)
Docker引擎:
json
{
  "builder": {
    "gc": {
      "enabled": true,
      "defaultKeepStorage": "20GB"
    }
  },
  "experimental": false,
  "features": {
    "buildkit": true
  }
}

macOS File Permissions

macOS文件权限

bash
undefined
bash
undefined

macOS user ID and group ID

macOS用户ID和组ID

id -u # Usually 501 id -g # Usually 20
id -u # 通常为501 id -g # 通常为20

Match in container

在容器中匹配权限

docker run --user 501:20 myimage
docker run --user 501:20 myimage

Or in Dockerfile

或在Dockerfile中配置

RUN adduser -u 501 -g 20 appuser USER appuser
undefined
RUN adduser -u 501 -g 20 appuser USER appuser
undefined

macOS Development Workflow

macOS开发工作流

yaml
undefined
yaml
undefined

docker-compose.yml for development

开发环境docker-compose.yml

version: '3.8'
services: app: build: . volumes: # Source code with delegated (better performance) - ./src:/app/src:delegated # node_modules in volume (much faster than bind mount) - node_modules:/app/node_modules ports: - "3000:3000" environment: - NODE_ENV=development
volumes: node_modules:
undefined
version: '3.8'
services: app: build: . volumes: # 源代码使用委托挂载(性能更佳) - ./src:/app/src:delegated # node_modules使用卷(比绑定挂载快得多) - node_modules:/app/node_modules ports: - "3000:3000" environment: - NODE_ENV=development
volumes: node_modules:
undefined

Common macOS Issues

macOS常见问题

Problem: Slow file sync Solution:
  • Use VirtioFS
  • Use delegated/cached mounts
  • Store dependencies in volumes (not bind mounts)
Problem: High CPU usage Solution:
  • Reduce file watching
  • Exclude large directories from file sharing
  • Allocate more resources
Problem: Port already in use Solution:
bash
undefined
问题:文件同步缓慢 解决方案:
  • 使用VirtioFS
  • 使用委托/缓存挂载
  • 将依赖存储在卷中(而非绑定挂载)
问题:CPU占用过高 解决方案:
  • 减少文件监听
  • 排除大型目录的文件共享
  • 分配更多资源
问题:端口已被占用 解决方案:
bash
undefined

Find process using port

查找占用端口的进程

lsof -i :PORT kill -9 PID
undefined
lsof -i :PORT kill -9 PID
undefined

Windows

Windows

Windows Container Types

Windows容器类型

1. Linux Containers on Windows (LCOW):
  • Most common for development
  • Uses WSL2 or Hyper-V backend
  • Runs Linux containers
  • Good compatibility
2. Windows Containers:
  • Native Windows containers
  • For Windows-specific workloads
  • Requires Windows Server base images
  • Less common in development
1. Windows上的Linux容器(LCOW):
  • 开发中最常用
  • 使用WSL2或Hyper-V后端
  • 运行Linux容器
  • 兼容性良好
2. Windows容器:
  • 原生Windows容器
  • 适用于Windows专属工作负载
  • 需要Windows Server基础镜像
  • 开发中使用较少

Windows Backend Options

Windows后端选项

WSL2 Backend (Recommended):
  • Faster
  • Better resource usage
  • Native Linux kernel
  • Requires Windows 10/11 (recent versions)
Hyper-V Backend:
  • Older option
  • More resource intensive
  • Works on older Windows versions
WSL2后端(推荐):
  • 速度更快
  • 资源使用更高效
  • 原生Linux内核
  • 需要Windows 10/11(最新版本)
Hyper-V后端:
  • 较旧的选项
  • 资源消耗更大
  • 适用于旧版Windows

WSL2 Configuration

WSL2配置

Enable WSL2:
powershell
undefined
启用WSL2:
powershell
undefined

Run as Administrator

以管理员身份运行

wsl --install
wsl --install

Or manually

或手动启用

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Set WSL2 as default

设置WSL2为默认版本

wsl --set-default-version 2
wsl --set-default-version 2

Install Ubuntu (or other distro)

安装Ubuntu(或其他发行版)

wsl --install -d Ubuntu

**Docker Desktop Integration:**
Settings → Resources → WSL Integration
  • Enable integration with default distro
  • Select additional distros
undefined
wsl --install -d Ubuntu

**Docker Desktop集成:**
设置 → 资源 → WSL集成
  • 启用与默认发行版的集成
  • 选择其他需要集成的发行版
undefined

Windows Path Considerations

Windows路径注意事项

Path Formats:
bash
undefined
路径格式:
bash
undefined

Forward slashes (recommended, works everywhere)

正斜杠(推荐,全平台通用)

docker run -v C:/Users/name/project:/app myimage
docker run -v C:/Users/name/project:/app myimage

Backslashes (need escaping in some contexts)

反斜杠(部分场景需要转义)

docker run -v C:\Users\name\project:/app myimage
docker run -v C:\Users\name\project:/app myimage

In docker-compose.yml (forward slashes)

在docker-compose.yml中使用正斜杠

volumes:
  • C:/Users/name/project:/app
volumes:
  • C:/Users/name/project:/app

Or relative paths

或相对路径

volumes:
  • ./src:/app/src
undefined
volumes:
  • ./src:/app/src
undefined

Git Bash / MINGW Path Conversion Issues

Git Bash / MINGW路径转换问题

CRITICAL ISSUE: When using Docker in Git Bash (MINGW) on Windows, automatic path conversion breaks volume mounts.
The Problem:
bash
undefined
严重问题: 在Windows上的Git Bash(MINGW)中使用Docker时,自动路径转换会破坏卷挂载。
问题表现:
bash
undefined

What you type in Git Bash:

你在Git Bash中输入的命令:

docker run -v $(pwd):/app myimage
docker run -v $(pwd):/app myimage

What Git Bash converts it to (BROKEN):

Git Bash转换后的错误命令:

docker run -v C:\Program Files\Git\d\repos\project:/app myimage

**Solutions:**

**1. MSYS_NO_PATHCONV (Recommended):**
```bash
docker run -v C:\Program Files\Git\d\repos\project:/app myimage

**解决方案:**

**1. MSYS_NO_PATHCONV(推荐):**
```bash

Per-command fix

单命令修复

MSYS_NO_PATHCONV=1 docker run -v $(pwd):/app myimage
MSYS_NO_PATHCONV=1 docker run -v $(pwd):/app myimage

Session-wide fix (add to ~/.bashrc)

会话级修复(添加到~/.bashrc)

export MSYS_NO_PATHCONV=1
export MSYS_NO_PATHCONV=1

Function wrapper (automatic for all Docker commands)

函数包装器(自动应用于所有Docker命令)

docker() { (export MSYS_NO_PATHCONV=1; command docker.exe "$@") } export -f docker

**2. Double Slash Workaround:**
```bash
docker() { (export MSYS_NO_PATHCONV=1; command docker.exe "$@") } export -f docker

**2. 双斜杠 workaround:**
```bash

Use double leading slash to prevent conversion

使用双前斜杠防止转换

docker run -v //c/Users/project:/app myimage
docker run -v //c/Users/project:/app myimage

Works with $(pwd) too

配合$(pwd)使用

docker run -v //$(pwd):/app myimage

**3. Named Volumes (No Path Issues):**
```bash
docker run -v //$(pwd):/app myimage

**3. 命名卷(无路径问题):**
```bash

Named volumes work without any fixes

命名卷无需任何修复即可正常使用

docker run -v my-data:/data myimage

**What Works Without Modification:**
- Docker Compose YAML files with relative paths
- Named volumes
- Network and image commands
- Container commands without volumes

**What Needs MSYS_NO_PATHCONV:**
- Bind mounts with `$(pwd)`
- Bind mounts with absolute Unix-style paths
- Volume mounts specified on command line

**Shell Detection:**
```bash
docker run -v my-data:/data myimage

**无需修改即可正常工作的场景:**
- 使用相对路径的Docker Compose YAML文件
- 命名卷
- 网络和镜像命令
- 无卷挂载的容器命令

**需要设置MSYS_NO_PATHCONV的场景:**
- 使用$(pwd)的绑定挂载
- 使用Unix风格绝对路径的绑定挂载
- 命令行中指定的卷挂载

**Shell检测:**
```bash

Detect Git Bash/MINGW and auto-configure

检测Git Bash/MINGW并自动配置

if [ -n "$MSYSTEM" ] || [[ "$(uname -s)" == MINGW* ]]; then export MSYS_NO_PATHCONV=1 echo "Git Bash detected - Docker path conversion fix enabled" fi

**Recommended ~/.bashrc Configuration:**
```bash
if [ -n "$MSYSTEM" ] || [[ "$(uname -s)" == MINGW* ]]; then export MSYS_NO_PATHCONV=1 echo "检测到Git Bash - Docker路径转换修复已启用" fi

**推荐的~/.bashrc配置:**
```bash

Docker on Git Bash fix

Git Bash上的Docker修复

if [ -n "$MSYSTEM" ]; then export MSYS_NO_PATHCONV=1 fi

See the `docker-git-bash-guide` skill for comprehensive path conversion documentation, troubleshooting, and examples.
if [ -n "$MSYSTEM" ]; then export MSYS_NO_PATHCONV=1 fi

如需全面的路径转换文档、故障排除及示例,请查看`docker-git-bash-guide`指南。

Windows File Sharing

Windows文件共享

Configure Shared Drives:
Docker Desktop → Settings → Resources → File Sharing
Add: C:\, D:\, etc.
Performance Considerations:
  • File sharing is slower than Linux/Mac
  • Use WSL2 backend for better performance
  • Store frequently accessed files in WSL2 filesystem
配置共享驱动器:
Docker Desktop → 设置 → 资源 → 文件共享
添加:C:\、D:\等
性能注意事项:
  • 文件共享速度慢于Linux/Mac
  • 使用WSL2后端可提升性能
  • 将频繁访问的文件存储在WSL2文件系统中

Windows Line Endings

Windows行尾符

Problem: CRLF vs LF line endings
Solution:
bash
undefined
问题:CRLF与LF行尾符差异 解决方案:
bash
undefined

Git configuration

Git配置

git config --global core.autocrlf input
git config --global core.autocrlf input

Or per-repo (.gitattributes)

或仓库级配置(.gitattributes)

  • text=auto *.sh text eol=lf *.bat text eol=crlf

```dockerfile
  • text=auto *.sh text eol=lf *.bat text eol=crlf

```dockerfile

In Dockerfile for scripts

在Dockerfile中处理脚本

FROM alpine COPY --chmod=755 script.sh /
FROM alpine COPY --chmod=755 script.sh /

Ensure LF endings

确保LF行尾符

RUN dos2unix /script.sh || sed -i 's/\r$//' /script.sh
undefined
RUN dos2unix /script.sh || sed -i 's/\r$//' /script.sh
undefined

Windows Firewall

Windows防火墙

powershell
undefined
powershell
undefined

Allow Docker Desktop

允许Docker Desktop通过防火墙

New-NetFirewallRule -DisplayName "Docker Desktop" -Direction Inbound -Program "C:\Program Files\Docker\Docker\Docker Desktop.exe" -Action Allow
New-NetFirewallRule -DisplayName "Docker Desktop" -Direction Inbound -Program "C:\Program Files\Docker\Docker\Docker Desktop.exe" -Action Allow

Check blocked ports

检查被占用的端口

netstat -ano | findstr :PORT
undefined
netstat -ano | findstr :PORT
undefined

Windows-Specific Docker Commands

Windows专属Docker命令

powershell
undefined
powershell
undefined

Run PowerShell in container

在容器中运行PowerShell

docker run -it mcr.microsoft.com/powershell:lts-7.4-windowsservercore-ltsc2022
docker run -it mcr.microsoft.com/powershell:lts-7.4-windowsservercore-ltsc2022

Windows container example

Windows容器示例

docker run -it mcr.microsoft.com/windows/servercore:ltsc2022 cmd
docker run -it mcr.microsoft.com/windows/servercore:ltsc2022 cmd

Check container type

检查容器类型

docker info | Select-String "OSType"
undefined
docker info | Select-String "OSType"
undefined

WSL2 Disk Management

WSL2磁盘管理

Problem: WSL2 VHDX grows but doesn't shrink
Solution:
powershell
undefined
问题:WSL2 VHDX文件只增不减 解决方案:
powershell
undefined

Stop Docker Desktop and WSL

停止Docker Desktop和WSL

wsl --shutdown
wsl --shutdown

Compact disk image (run as Administrator)

压缩磁盘镜像(以管理员身份运行)

Method 1: Optimize-VHD (requires Hyper-V tools)

方法1:Optimize-VHD(需要Hyper-V工具)

Optimize-VHD -Path "$env:LOCALAPPDATA\Docker\wsl\data\ext4.vhdx" -Mode Full
Optimize-VHD -Path "$env:LOCALAPPDATA\Docker\wsl\data\ext4.vhdx" -Mode Full

Method 2: diskpart

方法2:diskpart

diskpart
diskpart

In diskpart:

在diskpart中执行:

select vdisk file="C:\Users\YourName\AppData\Local\Docker\wsl\data\ext4.vhdx" attach vdisk readonly compact vdisk detach vdisk exit
undefined
select vdisk file="C:\Users\YourName\AppData\Local\Docker\wsl\data\ext4.vhdx" attach vdisk readonly compact vdisk detach vdisk exit
undefined

Windows Development Workflow

Windows开发工作流

yaml
undefined
yaml
undefined

docker-compose.yml for Windows

Windows环境docker-compose.yml

version: '3.8'
services: app: build: . volumes: # Use forward slashes - ./src:/app/src # Named volumes for better performance - node_modules:/app/node_modules ports: - "3000:3000" environment: - NODE_ENV=development # Windows-specific: ensure proper line endings command: sh -c "dos2unix /app/scripts/*.sh && npm start"
volumes: node_modules:
undefined
version: '3.8'
services: app: build: . volumes: # 使用正斜杠 - ./src:/app/src # 命名卷提升性能 - node_modules:/app/node_modules ports: - "3000:3000" environment: - NODE_ENV=development # Windows专属:确保正确的行尾符 command: sh -c "dos2unix /app/scripts/*.sh && npm start"
volumes: node_modules:
undefined

Common Windows Issues

Windows常见问题

Problem: Permission denied errors Solution:
powershell
undefined
问题:权限拒绝错误 解决方案:
powershell
undefined

Run Docker Desktop as Administrator

以管理员身份运行Docker Desktop

Or grant permissions to Docker Desktop

或为Docker Desktop授予权限

icacls "C:\ProgramData\DockerDesktop" /grant Users:F /T

**Problem:** Slow performance
**Solution:**
- Use WSL2 backend
- Store project in WSL2 filesystem (`\\wsl$\Ubuntu\home\user\project`)
- Use named volumes for node_modules, etc.

**Problem:** Path not found
**Solution:**
- Use forward slashes
- Ensure drive is shared in Docker Desktop
- Use absolute paths or `${PWD}`
icacls "C:\ProgramData\DockerDesktop" /grant Users:F /T

**问题:性能缓慢**
**解决方案:**
- 使用WSL2后端
- 将项目存储在WSL2文件系统中(`\\wsl$\Ubuntu\home\user\project`)
- 为node_modules等使用命名卷

**问题:路径未找到**
**解决方案:**
- 使用正斜杠
- 确保驱动器已在Docker Desktop中共享
- 使用绝对路径或`${PWD}`

Platform Comparison

平台对比

FeatureLinuxmacOSWindows
PerformanceExcellent (native)Good (VM overhead)Good (WSL2) to Fair (Hyper-V)
File sharingNativeSlow (improving with VirtioFS)Slow (better in WSL2)
Resource efficiencyBestGoodGood (WSL2)
Feature setCompleteCompleteComplete (LCOW)
ProductionStandardDev onlyDev only (LCOW)
Ease of useModerateEasy (Docker Desktop)Easy (Docker Desktop)
CostFreeFree (Docker Desktop Personal)Free (Docker Desktop Personal)
特性LinuxmacOSWindows
性能极佳(原生)良好(虚拟机开销)良好(WSL2)至一般(Hyper-V)
文件共享原生缓慢(VirtioFS已优化)缓慢(WSL2中表现更佳)
资源效率最佳良好良好(WSL2)
功能集完整完整完整(LCOW)
生产环境标准仅开发仅开发(LCOW)
易用性中等简单(Docker Desktop)简单(Docker Desktop)
成本免费免费(Docker Desktop个人版)免费(Docker Desktop个人版)

Cross-Platform Best Practices

跨平台最佳实践

Multi-Platform Images

多平台镜像

bash
undefined
bash
undefined

Create buildx builder

创建buildx构建器

docker buildx create --name multiplatform --driver docker-container --use
docker buildx create --name multiplatform --driver docker-container --use

Build for multiple platforms

构建多平台镜像

docker buildx build
--platform linux/amd64,linux/arm64,linux/arm/v7
-t myimage:latest
--push
.
undefined
docker buildx build
--platform linux/amd64,linux/arm64,linux/arm/v7
-t myimage:latest
--push
.
undefined

Platform-Agnostic Dockerfiles

平台无关Dockerfile

dockerfile
undefined
dockerfile
undefined

Works on all platforms

全平台通用

FROM node:20-alpine
FROM node:20-alpine

Use COPY with --chmod (not RUN chmod, which is slower)

使用COPY --chmod(比RUN chmod更快)

COPY --chmod=755 script.sh /usr/local/bin/
COPY --chmod=755 script.sh /usr/local/bin/

Use environment variables for paths

使用环境变量定义路径

ENV APP_HOME=/app WORKDIR ${APP_HOME}
ENV APP_HOME=/app WORKDIR ${APP_HOME}

Use exec form for CMD/ENTRYPOINT (works on Windows containers too)

使用exec格式的CMD/ENTRYPOINT(同样适用于Windows容器)

CMD ["node", "server.js"]
undefined
CMD ["node", "server.js"]
undefined

Cross-Platform Compose Files

跨平台Compose文件

yaml
version: '3.8'

services:
  app:
    build: .
    volumes:
      # Relative paths work everywhere
      - ./src:/app/src
      # Named volumes (platform-agnostic)
      - data:/app/data
    environment:
      # Use environment variables
      - NODE_ENV=${NODE_ENV:-development}

volumes:
  data:
yaml
version: '3.8'

services:
  app:
    build: .
    volumes:
      # 相对路径全平台通用
      - ./src:/app/src
      # 命名卷(平台无关)
      - data:/app/data
    environment:
      # 使用环境变量
      - NODE_ENV=${NODE_ENV:-development}

volumes:
  data:

Testing Across Platforms

跨平台测试

bash
undefined
bash
undefined

Test on different platforms with buildx

使用buildx在不同平台测试

docker buildx build --platform linux/amd64 -t myapp:amd64 --load . docker run --rm myapp:amd64
docker buildx build --platform linux/arm64 -t myapp:arm64 --load . docker run --rm myapp:arm64
undefined
docker buildx build --platform linux/amd64 -t myapp:amd64 --load . docker run --rm myapp:amd64
docker buildx build --platform linux/arm64 -t myapp:arm64 --load . docker run --rm myapp:arm64
undefined

Platform Selection Guide

平台选择指南

Choose Linux for:
  • Production deployments
  • Maximum performance
  • Full Docker feature set
  • Minimal overhead
  • CI/CD pipelines
Choose macOS for:
  • Development on Mac hardware
  • When you need macOS tools
  • Docker Desktop ease of use
  • M1/M2/M3 development
Choose Windows for:
  • Development on Windows hardware
  • Windows-specific applications
  • When team uses Windows
  • WSL2 for better Linux container support
This platform guide covers the major differences. Always test on your target deployment platform before going to production.
选择Linux的场景:
  • 生产部署
  • 追求最高性能
  • 需要完整的Docker功能集
  • 最小化开销
  • CI/CD流水线
选择macOS的场景:
  • 使用Mac硬件进行开发
  • 需要使用macOS工具
  • 偏好Docker Desktop的易用性
  • Apple Silicon(M1/M2/M3)开发
选择Windows的场景:
  • 使用Windows硬件进行开发
  • 开发Windows专属应用
  • 团队使用Windows环境
  • 借助WSL2获得更好的Linux容器支持
本平台指南涵盖了主要差异。上线生产环境前,请务必在目标部署平台上进行测试。