Docker容器架构
Docker容器架构
容器架构概览
Docker容器共享宿主机内核,通过namespace和cgroup实现资源隔离,比虚拟机更轻量高效。
┌─────────────────────────────────────────────┐
│ 宿主机内核 │
├───────────┬───────────┬─────────────────── │
│ Container │ Container │ Container │
│ A │ B │ C │
├───────────┼───────────┼─────────────────── │
│ App A │ App B │ App C │
│ Libs A │ Libs B │ Libs C │
│ Bins A │ Bins B │ Bins C │
└───────────┴───────────┴─────────────────── │
镜像分层
Docker镜像采用分层存储,共享基础层减少磁盘占用和拉取时间。
# 多阶段构建优化镜像
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
FROM node:18-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/index.js"]
网络模式
Docker提供bridge、host、overlay等多种网络模式满足不同场景。
# docker-compose网络配置
services:
web:
image: nginx:alpine
networks:
- frontend
api:
image: node:18-alpine
networks:
- frontend
- backend
db:
image: postgres:15
networks:
- backend
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true
存储管理
容器数据持久化通过Volume和Bind Mount实现。
# 存储配置
services:
db:
image: postgres:15
volumes:
- db-data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
environment:
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
volumes:
db-data:
driver: local
driver_opts:
type: nfs
o: addr=10.0.0.10,rw
device: ":/exports/db-data"
容器安全
# 安全最佳实践
FROM node:18-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
COPY --chown=appuser:appgroup . .
USER appuser
EXPOSE 3000
CMD ["node", "index.js"]
Docker Compose
# 生产环境配置
services:
app:
build: .
deploy:
resources:
limits:
cpus: '2'
memory: 1G
reservations:
cpus: '1'
memory: 512M
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3