c4-level2-container
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseC4 Level 2: Container Diagram & Infrastructure Mapping
C4第2级:容器图与基础设施映射
The Container diagram represents the high-level technical architecture — web apps, mobile apps, databases, background jobs, message brokers. In C4, "Container" means a separately deployable/runnable unit, NOT Docker (though Docker containers often map 1:1).
"A container is something that needs to be running in order for the overall software system to work." — Simon Brown
容器图代表了高层次的技术架构——Web应用、移动应用、数据库、后台任务、消息队列。在C4模型中,“Container”指的是可独立部署/运行的单元,而非Docker(不过Docker容器通常与它是1:1对应的)。
“容器是整体软件系统运行所必需的运行单元。”——Simon Brown
🎯 Stakeholder Focus
🎯 利益相关方关注点
| Stakeholder | What they need from L2 | Questions they ask |
|---|---|---|
| Architects | Tech decisions, API boundaries | "Why Go for API and React for frontend?" |
| Developers | System structure, cross-app communication | "How do services talk to each other?" |
| Ops/DevOps | Deployment strategy, infrastructure | "How many containers? What needs monitoring?" |
| Security | Trust boundaries, data flow | "What protocols encrypt data in transit?" |
| 利益相关方 | 他们从第2级图中需要什么 | 他们常问的问题 |
|---|---|---|
| 架构师 | 技术决策、API边界 | “为什么API用Go,前端用React?” |
| 开发人员 | 系统结构、跨应用通信 | “服务之间如何通信?” |
| 运维/DevOps | 部署策略、基础设施 | “有多少个容器?哪些需要监控?” |
| 安全人员 | 信任边界、数据流 | “传输中的数据用什么协议加密?” |
🏗️ Container Types & Mapping
🏗️ 容器类型与映射
| Container Type | Description | Maps To | Example Tech |
|---|---|---|---|
| Web Application | Browser-based UI | Build artifact (SPA bundle) | React, Vue, Angular |
| Mobile App | Native or cross-platform mobile | App store binary | iOS (Swift), Android (Kotlin), Flutter |
| API Application | HTTP/gRPC API server | Docker container, K8s deployment | Go, Python/FastAPI, Node.js/Express, Java/Spring |
| Database | Persistent data store | Managed DB, persistent volume | PostgreSQL, MySQL, MongoDB, Redis |
| Message Broker | Async messaging | K8s StatefulSet, managed service | Kafka, RabbitMQ, AWS SQS, NATS |
| File Store | Object/blob storage | Cloud bucket, NFS | S3, GCS, Azure Blob |
| Background Worker | Async job processor | K8s CronJob, queue consumer | Celery, Sidekiq, Go worker |
| Cache | In-memory data | Redis/Memcached instance | Redis, Memcached |
| 容器类型 | 描述 | 对应基础设施 | 技术示例 |
|---|---|---|---|
| Web应用 | 基于浏览器的UI | 构建产物(SPA包) | React, Vue, Angular |
| 移动应用 | 原生或跨平台移动应用 | 应用商店二进制包 | iOS(Swift)、Android(Kotlin)、Flutter |
| API应用 | HTTP/gRPC API服务器 | Docker容器、K8s Deployment | Go、Python/FastAPI、Node.js/Express、Java/Spring |
| 数据库 | 持久化数据存储 | 托管数据库、持久化卷 | PostgreSQL, MySQL, MongoDB, Redis |
| 消息队列 | 异步消息传递 | K8s StatefulSet、托管服务 | Kafka, RabbitMQ, AWS SQS, NATS |
| 文件存储 | 对象/Blob存储 | 云存储桶、NFS | S3, GCS, Azure Blob |
| 后台工作进程 | 异步任务处理器 | K8s CronJob、队列消费者 | Celery, Sidekiq, Go worker |
| 缓存 | 内存数据存储 | Redis/Memcached实例 | Redis, Memcached |
Infrastructure Mapping Rules
基础设施映射规则
L2 Container → Infrastructure Artifact
─────────────────────────────────────────────────────
Web App → Docker image + Nginx/CDN
API Service → Docker container + K8s Deployment
Database → Cloud SQL / RDS / Persistent Volume
Message Broker → K8s StatefulSet / Managed Service
Background Worker → K8s CronJob / Queue Consumer
Cache → Redis Cluster / ElastiCacheL2 Container → Infrastructure Artifact
─────────────────────────────────────────────────────
Web App → Docker image + Nginx/CDN
API Service → Docker container + K8s Deployment
Database → Cloud SQL / RDS / Persistent Volume
Message Broker → K8s StatefulSet / Managed Service
Background Worker → K8s CronJob / Queue Consumer
Cache → Redis Cluster / ElastiCache🚫 Anti-Patterns to Guard (Level 2)
🚫 需避免的反模式(第2级)
| Anti-Pattern | Symptom | Fix |
|---|---|---|
| Flowchart Confusion | Business logic steps in diagram | Use sequence diagram for flows. L2 shows structure, not process |
| Library as Container | "Shared Utils", "Common Library" as boxes | Libraries are code (L3/L4), not deployable units |
| Diagram Overload | >10 containers in one view | Split: "Customer View", "Admin View", "Data Pipeline View" |
| Missing Protocols | Arrows without labels | Every arrow needs protocol: "JSON/HTTPS", "gRPC/TCP", "SQL/TCP" |
| Shared Database | Multiple containers → one DB without ownership | Each container should own its data. Shared DB = tight coupling |
| Missing Boundaries | Containers floating without system boundary | Wrap in |
| 反模式 | 症状 | 修复方案 |
|---|---|---|
| 流程图混淆 | 图中包含业务逻辑步骤 | 用序列图展示流程。第2级图展示结构,而非流程 |
| 将库视为容器 | 将“共享工具库”、“通用库”作为框图 | 库属于代码(第3/4级),而非可部署单元 |
| 图过载 | 单个视图中容器数量>10 | 拆分视图:“客户视图”、“管理员视图”、“数据流水线视图” |
| 缺少协议标注 | 箭头无标签 | 每个箭头都需要标注协议:“JSON/HTTPS”、“gRPC/TCP”、“SQL/TCP” |
| 共享数据库 | 多个容器指向同一个无归属的数据库 | 每个容器应拥有自己的数据。共享数据库会导致紧耦合 |
| 缺少边界 | 容器无系统边界包裹 | 用 |
🔍 Codebase Scanning (L2 Synthesis)
🔍 代码库扫描(第2级综合分析)
To identify containers in an existing codebase, scan for:
要在现有代码库中识别容器,可扫描以下内容:
Build Manifests (Tech Stack)
构建清单(技术栈)
bash
undefinedbash
undefinedJavaScript/TypeScript
JavaScript/TypeScript
package.json → frontend framework, backend runtime
package.json → 前端框架、后端运行时
Go
Go
go.mod → modules, HTTP framework (gin, echo, chi)
go.mod → 模块、HTTP框架(gin, echo, chi)
Java
Java
pom.xml / build.gradle → Spring Boot, dependencies
pom.xml / build.gradle → Spring Boot、依赖项
Python
Python
requirements.txt / pyproject.toml → FastAPI, Django, Flask
undefinedrequirements.txt / pyproject.toml → FastAPI, Django, Flask
undefinedDeployment Artifacts
部署产物
bash
Dockerfile → Container definition
docker-compose.yml → Multi-container setup
k8s/ → Kubernetes manifests
terraform/ → Infrastructure as Code
serverless.yml → Serverless functions (Lambda, etc.)bash
Dockerfile → 容器定义
docker-compose.yml → 多容器配置
k8s/ → Kubernetes清单
terraform/ → 基础设施即代码
serverless.yml → 无服务器函数(Lambda等)Service Boundaries
服务边界
bash
undefinedbash
undefinedLook for separate entry points
寻找独立入口点
src/main.go → API service
cmd/worker/main.go → Background worker
web/ → Frontend application
---src/main.go → API服务
cmd/worker/main.go → 后台工作进程
web/ → 前端应用
---📝 Mermaid Templates
📝 Mermaid模板
Template A: Monolith with Frontend
模板A:带前端的单体应用
mermaid
C4Container
title Container Diagram for E-Commerce Platform
Person(customer, "Customer", "Registered user browsing products.")
System_Boundary(ecommerce, "E-Commerce Platform") {
Container(web_app, "Web Application", "React/TypeScript", "Customer-facing SPA.")
Container(api, "API Service", "Go/gRPC", "Business logic, authentication, order processing.")
ContainerDb(db, "Primary Database", "PostgreSQL", "Users, products, orders, inventory.")
Container(cache, "Cache", "Redis", "Session store, product catalog cache.")
Container(worker, "Order Processor", "Go", "Processes payment confirmation, sends emails.")
ContainerQueue(queue, "Message Queue", "RabbitMQ", "Async order events.")
}
System_Ext(payment, "Payment Gateway", "Stripe/PayPal")
System_Ext(email, "Email Service", "SendGrid")
Rel(customer, web_app, "Browses, purchases", "HTTPS")
Rel(web_app, api, "Calls API", "JSON/HTTPS")
Rel(api, db, "Reads/Writes", "SQL/TCP")
Rel(api, cache, "Caches data", "Redis Protocol")
Rel(api, queue, "Publishes events", "AMQP")
Rel(worker, queue, "Consumes events", "AMQP")
Rel(worker, email, "Sends emails", "REST API/HTTPS")
Rel(api, payment, "Processes payments", "REST API/HTTPS")mermaid
C4Container
title Container Diagram for E-Commerce Platform
Person(customer, "Customer", "Registered user browsing products.")
System_Boundary(ecommerce, "E-Commerce Platform") {
Container(web_app, "Web Application", "React/TypeScript", "Customer-facing SPA.")
Container(api, "API Service", "Go/gRPC", "Business logic, authentication, order processing.")
ContainerDb(db, "Primary Database", "PostgreSQL", "Users, products, orders, inventory.")
Container(cache, "Cache", "Redis", "Session store, product catalog cache.")
Container(worker, "Order Processor", "Go", "Processes payment confirmation, sends emails.")
ContainerQueue(queue, "Message Queue", "RabbitMQ", "Async order events.")
}
System_Ext(payment, "Payment Gateway", "Stripe/PayPal")
System_Ext(email, "Email Service", "SendGrid")
Rel(customer, web_app, "Browses, purchases", "HTTPS")
Rel(web_app, api, "Calls API", "JSON/HTTPS")
Rel(api, db, "Reads/Writes", "SQL/TCP")
Rel(api, cache, "Caches data", "Redis Protocol")
Rel(api, queue, "Publishes events", "AMQP")
Rel(worker, queue, "Consumes events", "AMQP")
Rel(worker, email, "Sends emails", "REST API/HTTPS")
Rel(api, payment, "Processes payments", "REST API/HTTPS")Template B: Microservices Architecture
模板B:微服务架构
mermaid
C4Container
title Container Diagram for Microservices Platform
Person(customer, "Customer", "End user of the platform.")
Container(api_gateway, "API Gateway", "Kong/AWS API Gateway", "Routing, rate limiting, auth.")
Container(web_app, "Web App", "Next.js", "Customer-facing UI.")
System_Boundary(platform, "Platform Services") {
Container(user_svc, "User Service", "Go/gRPC", "User profiles, authentication.")
Container(order_svc, "Order Service", "Go/gRPC", "Order creation, status tracking.")
Container(product_svc, "Product Service", "Python/FastAPI", "Product catalog, search.")
Container(inventory_svc, "Inventory Service", "Go/gRPC", "Stock levels, reservations.")
Container(notification_svc, "Notification Service", "Node.js", "Email, SMS, push notifications.")
ContainerDb(user_db, "User DB", "PostgreSQL", "User data.")
ContainerDb(order_db, "Order DB", "PostgreSQL", "Order data.")
ContainerDb(product_db, "Product DB", "MongoDB", "Product documents.")
ContainerDb(inventory_db, "Inventory DB", "PostgreSQL", "Stock data.")
ContainerQueue(event_bus, "Event Bus", "Kafka", "Domain events between services.")
}
System_Ext(payment, "Payment Gateway", "Stripe")
System_Ext(search, "Search Engine", "Elasticsearch")
Rel(customer, web_app, "Uses", "HTTPS")
Rel(web_app, api_gateway, "Calls APIs", "JSON/HTTPS")
Rel(api_gateway, user_svc, "Routes to", "gRPC/TLS")
Rel(api_gateway, order_svc, "Routes to", "gRPC/TLS")
Rel(api_gateway, product_svc, "Routes to", "gRPC/TLS")
Rel(user_svc, user_db, "Reads/Writes", "SQL/TCP")
Rel(order_svc, order_db, "Reads/Writes", "SQL/TCP")
Rel(product_svc, product_db, "Reads/Writes", "MongoDB Protocol")
Rel(inventory_svc, inventory_db, "Reads/Writes", "SQL/TCP")
Rel(order_svc, event_bus, "Publishes OrderPlaced", "Kafka Protocol")
Rel(inventory_svc, event_bus, "Consumes OrderPlaced", "Kafka Protocol")
Rel(notification_svc, event_bus, "Consumes OrderPlaced", "Kafka Protocol")
Rel(order_svc, payment, "Processes payment", "REST API/HTTPS")
Rel(product_svc, search, "Indexes products", "REST API/HTTPS")mermaid
C4Container
title Container Diagram for Microservices Platform
Person(customer, "Customer", "End user of the platform.")
Container(api_gateway, "API Gateway", "Kong/AWS API Gateway", "Routing, rate limiting, auth.")
Container(web_app, "Web App", "Next.js", "Customer-facing UI.")
System_Boundary(platform, "Platform Services") {
Container(user_svc, "User Service", "Go/gRPC", "User profiles, authentication.")
Container(order_svc, "Order Service", "Go/gRPC", "Order creation, status tracking.")
Container(product_svc, "Product Service", "Python/FastAPI", "Product catalog, search.")
Container(inventory_svc, "Inventory Service", "Go/gRPC", "Stock levels, reservations.")
Container(notification_svc, "Notification Service", "Node.js", "Email, SMS, push notifications.")
ContainerDb(user_db, "User DB", "PostgreSQL", "User data.")
ContainerDb(order_db, "Order DB", "PostgreSQL", "Order data.")
ContainerDb(product_db, "Product DB", "MongoDB", "Product documents.")
ContainerDb(inventory_db, "Inventory DB", "PostgreSQL", "Stock data.")
ContainerQueue(event_bus, "Event Bus", "Kafka", "Domain events between services.")
}
System_Ext(payment, "Payment Gateway", "Stripe")
System_Ext(search, "Search Engine", "Elasticsearch")
Rel(customer, web_app, "Uses", "HTTPS")
Rel(web_app, api_gateway, "Calls APIs", "JSON/HTTPS")
Rel(api_gateway, user_svc, "Routes to", "gRPC/TLS")
Rel(api_gateway, order_svc, "Routes to", "gRPC/TLS")
Rel(api_gateway, product_svc, "Routes to", "gRPC/TLS")
Rel(user_svc, user_db, "Reads/Writes", "SQL/TCP")
Rel(order_svc, order_db, "Reads/Writes", "SQL/TCP")
Rel(product_svc, product_db, "Reads/Writes", "MongoDB Protocol")
Rel(inventory_svc, inventory_db, "Reads/Writes", "SQL/TCP")
Rel(order_svc, event_bus, "Publishes OrderPlaced", "Kafka Protocol")
Rel(inventory_svc, event_bus, "Consumes OrderPlaced", "Kafka Protocol")
Rel(notification_svc, event_bus, "Consumes OrderPlaced", "Kafka Protocol")
Rel(order_svc, payment, "Processes payment", "REST API/HTTPS")
Rel(product_svc, search, "Indexes products", "REST API/HTTPS")Template C: Serverless / Event-Driven
模板C:无服务器/事件驱动架构
mermaid
C4Container
title Container Diagram for Serverless Data Pipeline
Person(analyst, "Data Analyst", "Consumes processed data.")
System_Boundary(pipeline, "Data Pipeline") {
Container(ingestion, "Ingestion Function", "AWS Lambda / Python", "Receives and validates incoming data.")
Container(transform, "Transform Function", "AWS Lambda / Python", "Cleans and enriches data.")
Container(store, "Data Store", "S3", "Raw and processed data files.")
Container(warehouse, "Data Warehouse", "Snowflake", "Structured data for analytics.")
Container(scheduler, "Scheduler", "AWS EventBridge", "Triggers pipeline runs.")
}
System_Ext(source, "Data Source", "External API / SFTP")
System_Ext(dashboard, "BI Dashboard", "Tableau / Looker")
Rel(source, ingestion, "Pushes data", "HTTPS / SFTP")
Rel(scheduler, ingestion, "Triggers", "EventBridge")
Rel(ingestion, store, "Stores raw", "S3 API")
Rel(ingestion, transform, "Invokes", "Lambda Invoke")
Rel(transform, warehouse, "Loads processed", "Snowflake SQL")
Rel(analyst, dashboard, "Views reports", "HTTPS")
Rel(dashboard, warehouse, "Queries", "SQL/JDBC")mermaid
C4Container
title Container Diagram for Serverless Data Pipeline
Person(analyst, "Data Analyst", "Consumes processed data.")
System_Boundary(pipeline, "Data Pipeline") {
Container(ingestion, "Ingestion Function", "AWS Lambda / Python", "Receives and validates incoming data.")
Container(transform, "Transform Function", "AWS Lambda / Python", "Cleans and enriches data.")
Container(store, "Data Store", "S3", "Raw and processed data files.")
Container(warehouse, "Data Warehouse", "Snowflake", "Structured data for analytics.")
Container(scheduler, "Scheduler", "AWS EventBridge", "Triggers pipeline runs.")
}
System_Ext(source, "Data Source", "External API / SFTP")
System_Ext(dashboard, "BI Dashboard", "Tableau / Looker")
Rel(source, ingestion, "Pushes data", "HTTPS / SFTP")
Rel(scheduler, ingestion, "Triggers", "EventBridge")
Rel(ingestion, store, "Stores raw", "S3 API")
Rel(ingestion, transform, "Invokes", "Lambda Invoke")
Rel(transform, warehouse, "Loads processed", "Snowflake SQL")
Rel(analyst, dashboard, "Views reports", "HTTPS")
Rel(dashboard, warehouse, "Queries", "SQL/JDBC")🏗️ Deployment Patterns
🏗️ 部署模式
Pattern 1: Single Monolith
模式1:单体应用
┌─────────────────────────────┐
│ Load Balancer │
└─────────────┬───────────────┘
│
┌─────────┴─────────┐
│ Monolithic App │
│ (Web + API + │
│ Background) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Database │
└───────────────────┘When to use: Small team (<5), simple domain, rapid prototyping.
┌─────────────────────────────┐
│ Load Balancer │
└─────────────┬───────────────┘
│
┌─────────┴─────────┐
│ Monolithic App │
│ (Web + API + │
│ Background) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Database │
└───────────────────┘适用场景: 小团队(<5人)、简单业务领域、快速原型开发。
Pattern 2: Frontend + Backend Split
模式2:前端+后端拆分
┌─────────────┐ ┌─────────────┐
│ CDN/Web │────▶│ API │
│ (React) │ │ (Go/Java) │
└─────────────┘ └──────┬──────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│ DB │ │ Cache │ │ Queue │
└────────┘ └────────┘ └────────┘When to use: Separate frontend/backend teams, different deployment cadences.
┌─────────────┐ ┌─────────────┐
│ CDN/Web │────▶│ API │
│ (React) │ │ (Go/Java) │
└─────────────┘ └──────┬──────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│ DB │ │ Cache │ │ Queue │
└────────┘ └────────┘ └────────┘适用场景: 前端/后端团队分离、不同的部署节奏。
Pattern 3: Microservices with API Gateway
模式3:带API网关的微服务
┌─────────────┐
│ API Gateway │
│ (Kong/AWS) │
└──────┬──────┘
│
┌──────────────────┼──────────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Service │ │ Service │ │ Service │
│ A │ │ B │ │ C │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ DB A │ │ DB B │ │ DB C │
└─────────┘ └─────────┘ └─────────┘When to use: Multiple teams, independent deployability, complex domain.
┌─────────────┐
│ API Gateway │
│ (Kong/AWS) │
└──────┬──────┘
│
┌──────────────────┼──────────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Service │ │ Service │ │ Service │
│ A │ │ B │ │ C │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ DB A │ │ DB B │ │ DB C │
└─────────┘ └─────────┘ └─────────┘适用场景: 多团队协作、独立部署、复杂业务领域。
✅ Level 2 Success Criteria
✅ 第2级成功标准
- Are all containers separately deployable/runnable units?
- Are all cross-container protocols (JSON, SQL, gRPC) specified?
- Is the diagram readable (≤10 containers per view)?
- SMART: Do containers match build/deployment artifacts in the code?
- SMART: Does each container own its data (no shared DB)?
- Are external systems clearly marked?
- Is there a system boundary around owned containers?
- 所有容器是否都是可独立部署/运行的单元?
- 所有跨容器的协议(JSON、SQL、gRPC)是否已明确标注?
- 图是否易读(每个视图≤10个容器)?
- SMART: 容器是否与代码中的构建/部署产物匹配?
- SMART: 每个容器是否拥有自己的数据(无共享数据库)?
- 外部系统是否已清晰标记?
- 自有容器是否有系统边界包裹?
🔄 From L2 to L3
🔄 从第2级到第3级
When you're ready to zoom into a container:
| L2 Signal | L3 Action |
|---|---|
| "This container has 5+ responsibilities" | Split into components |
| "Developers don't understand internal structure" | Draw component diagram |
| "We have circular imports" | L3 reveals dependency cycles |
| "This is our Core Domain" | Deep dive with |
Next: Use to design internal architecture.
c4-level3-component当你准备深入某个容器时:
| 第2级信号 | 第3级行动 |
|---|---|
| “这个容器有5项以上职责” | 拆分为组件 |
| “开发人员不理解其内部结构” | 绘制组件图 |
| “我们存在循环依赖” | 第3级图会揭示依赖循环 |
| “这是我们的核心业务领域” | 用 |
下一步: 使用设计内部架构。
c4-level3-component📚 References
📚 参考资料
- C4 Model — Container Diagram — Simon Brown
- Structurizr DSL — Container View
- Building Microservices — Sam Newman
- C4 Model — Container Diagram — Simon Brown
- Structurizr DSL — Container View
- Building Microservices — Sam Newman