docker-management

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Docker Management

Docker 管理

Build, run, and manage Docker containers for application deployment and development.
为应用部署和开发构建、运行及管理Docker容器。

When to Use This Skill

何时使用此技能

Use this skill when:
  • Creating and optimizing Dockerfiles
  • Building and tagging Docker images
  • Running and managing containers
  • Debugging container issues
  • Configuring Docker networking and volumes
  • Implementing container security best practices
在以下场景使用此技能:
  • 创建和优化Dockerfile
  • 构建并标记Docker镜像
  • 运行并管理容器
  • 调试容器问题
  • 配置Docker网络和卷
  • 实施容器安全最佳实践

Prerequisites

前提条件

  • Docker Engine installed (20.10+)
  • Basic command line knowledge
  • Understanding of application deployment
  • 已安装Docker Engine(20.10及以上版本)
  • 具备基础命令行知识
  • 了解应用部署相关知识

Dockerfile Best Practices

Dockerfile 最佳实践

Multi-Stage Build

多阶段构建

dockerfile
undefined
dockerfile
undefined

Build stage

Build stage

FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . RUN npm run build
FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . RUN npm run build

Production stage

Production stage

FROM node:20-alpine AS production WORKDIR /app RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001 COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules USER nodejs EXPOSE 3000 CMD ["node", "dist/index.js"]
undefined
FROM node:20-alpine AS production WORKDIR /app RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001 COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules USER nodejs EXPOSE 3000 CMD ["node", "dist/index.js"]
undefined

Layer Optimization

层优化

dockerfile
FROM python:3.12-slim
dockerfile
FROM python:3.12-slim

Install dependencies first (cached unless requirements change)

Install dependencies first (cached unless requirements change)

COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt

Copy application code (changes frequently)

Copy application code (changes frequently)

COPY . .
CMD ["python", "app.py"]
undefined
COPY . .
CMD ["python", "app.py"]
undefined

Security Hardening

安全加固

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

Create non-root user

Create non-root user

RUN addgroup -g 1001 appgroup &&
adduser -u 1001 -G appgroup -D appuser
WORKDIR /app
RUN addgroup -g 1001 appgroup &&
adduser -u 1001 -G appgroup -D appuser
WORKDIR /app

Copy with proper ownership

Copy with proper ownership

COPY --chown=appuser:appgroup . .
COPY --chown=appuser:appgroup . .

Drop privileges

Drop privileges

USER appuser
USER appuser

Use exec form for proper signal handling

Use exec form for proper signal handling

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

Building Images

构建镜像

Basic Build

基础构建

bash
undefined
bash
undefined

Build with tag

Build with tag

docker build -t myapp:1.0 .
docker build -t myapp:1.0 .

Build with build args

Build with build args

docker build --build-arg NODE_ENV=production -t myapp:prod .
docker build --build-arg NODE_ENV=production -t myapp:prod .

Build for specific platform

Build for specific platform

docker build --platform linux/amd64 -t myapp:amd64 .
docker build --platform linux/amd64 -t myapp:amd64 .

Build with no cache

Build with no cache

docker build --no-cache -t myapp:fresh .
undefined
docker build --no-cache -t myapp:fresh .
undefined

Multi-Platform Builds

多平台构建

bash
undefined
bash
undefined

Create builder

Create builder

docker buildx create --name multiplatform --use
docker buildx create --name multiplatform --use

Build for multiple architectures

Build for multiple architectures

docker buildx build
--platform linux/amd64,linux/arm64
-t myregistry/myapp:latest
--push .
undefined
docker buildx build
--platform linux/amd64,linux/arm64
-t myregistry/myapp:latest
--push .
undefined

Running Containers

运行容器

Basic Operations

基础操作

bash
undefined
bash
undefined

Run container

Run container

docker run -d --name myapp -p 8080:3000 myapp:latest
docker run -d --name myapp -p 8080:3000 myapp:latest

Run with environment variables

Run with environment variables

docker run -d
-e DATABASE_URL=postgres://localhost/db
-e NODE_ENV=production
myapp:latest
docker run -d
-e DATABASE_URL=postgres://localhost/db
-e NODE_ENV=production
myapp:latest

Run with resource limits

Run with resource limits

docker run -d
--memory="512m"
--cpus="1.0"
myapp:latest
docker run -d
--memory="512m"
--cpus="1.0"
myapp:latest

Run with restart policy

Run with restart policy

docker run -d --restart=unless-stopped myapp:latest
undefined
docker run -d --restart=unless-stopped myapp:latest
undefined

Volume Management

卷管理

bash
undefined
bash
undefined

Named volume

Named volume

docker volume create mydata docker run -v mydata:/app/data myapp:latest
docker volume create mydata docker run -v mydata:/app/data myapp:latest

Bind mount

Bind mount

docker run -v $(pwd)/config:/app/config:ro myapp:latest
docker run -v $(pwd)/config:/app/config:ro myapp:latest

tmpfs mount (memory)

tmpfs mount (memory)

docker run --tmpfs /tmp:rw,noexec,nosuid myapp:latest
undefined
docker run --tmpfs /tmp:rw,noexec,nosuid myapp:latest
undefined

Networking

网络配置

bash
undefined
bash
undefined

Create network

Create network

docker network create mynetwork
docker network create mynetwork

Run on network

Run on network

docker run -d --network mynetwork --name api myapp:latest
docker run -d --network mynetwork --name api myapp:latest

Connect existing container

Connect existing container

docker network connect mynetwork existing-container
docker network connect mynetwork existing-container

Expose specific ports

Expose specific ports

docker run -d -p 127.0.0.1:8080:3000 myapp:latest
undefined
docker run -d -p 127.0.0.1:8080:3000 myapp:latest
undefined

Container Lifecycle

容器生命周期

Management Commands

管理命令

bash
undefined
bash
undefined

List containers

List containers

docker ps -a
docker ps -a

Stop container

Stop container

docker stop myapp
docker stop myapp

Remove container

Remove container

docker rm myapp
docker rm myapp

Force remove running container

Force remove running container

docker rm -f myapp
docker rm -f myapp

Prune stopped containers

Prune stopped containers

docker container prune -f
undefined
docker container prune -f
undefined

Logs and Monitoring

日志与监控

bash
undefined
bash
undefined

View logs

View logs

docker logs myapp
docker logs myapp

Follow logs

Follow logs

docker logs -f --tail 100 myapp
docker logs -f --tail 100 myapp

View resource usage

View resource usage

docker stats myapp
docker stats myapp

Inspect container

Inspect container

docker inspect myapp
undefined
docker inspect myapp
undefined

Debugging Containers

调试容器

Interactive Access

交互式访问

bash
undefined
bash
undefined

Execute command in running container

Execute command in running container

docker exec -it myapp /bin/sh
docker exec -it myapp /bin/sh

Run container with shell

Run container with shell

docker run -it --rm myapp:latest /bin/sh
docker run -it --rm myapp:latest /bin/sh

Debug failed container

Debug failed container

docker run -it --entrypoint /bin/sh myapp:latest
undefined
docker run -it --entrypoint /bin/sh myapp:latest
undefined

Troubleshooting

故障排查

bash
undefined
bash
undefined

Check container logs for errors

Check container logs for errors

docker logs myapp 2>&1 | grep -i error
docker logs myapp 2>&1 | grep -i error

Inspect container state

Inspect container state

docker inspect --format='{{.State.Status}}' myapp
docker inspect --format='{{.State.Status}}' myapp

Check container processes

Check container processes

docker top myapp
docker top myapp

View container filesystem changes

View container filesystem changes

docker diff myapp
docker diff myapp

Export container filesystem

Export container filesystem

docker export myapp > myapp-fs.tar
undefined
docker export myapp > myapp-fs.tar
undefined

Health Checks

健康检查

dockerfile
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1
bash
undefined
dockerfile
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1
bash
undefined

Check health status

Check health status

docker inspect --format='{{.State.Health.Status}}' myapp
undefined
docker inspect --format='{{.State.Health.Status}}' myapp
undefined

Image Management

镜像管理

Tagging and Pushing

标记与推送

bash
undefined
bash
undefined

Tag image

Tag image

docker tag myapp:latest myregistry.com/myapp:v1.0
docker tag myapp:latest myregistry.com/myapp:v1.0

Push to registry

Push to registry

docker push myregistry.com/myapp:v1.0
docker push myregistry.com/myapp:v1.0

Pull image

Pull image

docker pull myregistry.com/myapp:v1.0
undefined
docker pull myregistry.com/myapp:v1.0
undefined

Cleanup

清理

bash
undefined
bash
undefined

Remove unused images

Remove unused images

docker image prune -a
docker image prune -a

Remove all unused resources

Remove all unused resources

docker system prune -a --volumes
docker system prune -a --volumes

Remove specific image

Remove specific image

docker rmi myapp:old
docker rmi myapp:old

List image sizes

List image sizes

docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"
undefined
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"
undefined

Image Analysis

镜像分析

bash
undefined
bash
undefined

View image history

View image history

docker history myapp:latest
docker history myapp:latest

Inspect image layers

Inspect image layers

docker inspect myapp:latest
docker inspect myapp:latest

Check image vulnerabilities (with Docker Scout)

Check image vulnerabilities (with Docker Scout)

docker scout cves myapp:latest
undefined
docker scout cves myapp:latest
undefined

Docker Compose Integration

Docker Compose 集成

yaml
undefined
yaml
undefined

docker-compose.yml

docker-compose.yml

version: '3.8'
services: app: build: context: . dockerfile: Dockerfile ports: - "3000:3000" environment: - NODE_ENV=production volumes: - app-data:/app/data depends_on: - db restart: unless-stopped
db: image: postgres:15-alpine environment: POSTGRES_PASSWORD: secret volumes: - db-data:/var/lib/postgresql/data
volumes: app-data: db-data:
undefined
version: '3.8'
services: app: build: context: . dockerfile: Dockerfile ports: - "3000:3000" environment: - NODE_ENV=production volumes: - app-data:/app/data depends_on: - db restart: unless-stopped
db: image: postgres:15-alpine environment: POSTGRES_PASSWORD: secret volumes: - db-data:/var/lib/postgresql/data
volumes: app-data: db-data:
undefined

Security Best Practices

安全最佳实践

Image Security

镜像安全

dockerfile
undefined
dockerfile
undefined

Use specific version tags

Use specific version tags

FROM node:20.10-alpine3.18
FROM node:20.10-alpine3.18

Don't run as root

Don't run as root

USER nobody
USER nobody

Remove unnecessary packages

Remove unnecessary packages

RUN apk del --purge build-dependencies
RUN apk del --purge build-dependencies

Use COPY instead of ADD

Use COPY instead of ADD

COPY . .
undefined
COPY . .
undefined

Runtime Security

运行时安全

bash
undefined
bash
undefined

Run with security options

Run with security options

docker run -d
--security-opt=no-new-privileges
--cap-drop=ALL
--cap-add=NET_BIND_SERVICE
--read-only
myapp:latest
docker run -d
--security-opt=no-new-privileges
--cap-drop=ALL
--cap-add=NET_BIND_SERVICE
--read-only
myapp:latest

Use user namespace remapping

Use user namespace remapping

Add to /etc/docker/daemon.json: {"userns-remap": "default"}

Add to /etc/docker/daemon.json: {"userns-remap": "default"}

undefined
undefined

Common Issues

常见问题

Issue: Container Exits Immediately

问题:容器立即退出

Problem: Container starts and stops instantly Solution: Check if CMD/ENTRYPOINT runs foreground process, use
docker logs
to see errors
问题:容器启动后立即停止 解决方案:检查CMD/ENTRYPOINT是否运行前台进程,使用
docker logs
查看错误信息

Issue: Cannot Connect to Container

问题:无法连接到容器

Problem: Port not accessible Solution: Verify port mapping (-p), check container is running, verify firewall rules
问题:端口无法访问 解决方案:验证端口映射(-p参数),检查容器是否运行,验证防火墙规则

Issue: Out of Disk Space

问题:磁盘空间不足

Problem: Docker using too much disk Solution: Run
docker system prune -a --volumes
, check for large unused images
问题:Docker占用过多磁盘空间 解决方案:运行
docker system prune -a --volumes
,检查是否存在大型未使用镜像

Issue: Build Cache Not Working

问题:构建缓存未生效

Problem: Every build downloads dependencies Solution: Order Dockerfile instructions from least to most frequently changing
问题:每次构建都重新下载依赖 解决方案:将Dockerfile指令按变更频率从低到高排序

Best Practices

最佳实践

  • Use multi-stage builds to minimize image size
  • Never store secrets in images - use runtime injection
  • Pin base image versions for reproducibility
  • Implement health checks for production containers
  • Use .dockerignore to exclude unnecessary files
  • Run containers as non-root users
  • Scan images for vulnerabilities regularly
  • Use Docker BuildKit for faster builds
  • 使用多阶段构建最小化镜像体积
  • 切勿在镜像中存储密钥 - 使用运行时注入方式
  • 固定基础镜像版本以保证可复现性
  • 为生产容器实现健康检查
  • 使用.dockerignore排除不必要的文件
  • 以非root用户运行容器
  • 定期扫描镜像漏洞
  • 使用Docker BuildKit加速构建

Related Skills

相关技能

  • docker-compose - Multi-container applications
  • container-scanning - Security scanning
  • container-hardening - Security hardening
  • docker-compose - 多容器应用
  • container-scanning - 安全扫描
  • container-hardening - 安全加固