COMP5349 Cloud Computing — 复习讲义

详细知识点 + 例子 · 每句英文都配中文 · 对应考试 Q1–Q7
点标题可折叠该节 / click a heading to fold

1 · 虚拟化 & EC2 考试 Q1 选择题

虚拟化基础

  • Hypervisor = the abstraction/isolation layer that allocates, isolates and manages hardware for VMs; all hardware access goes through it. Hypervisor(虚拟机管理程序)=抽象与隔离层,为虚拟机分配、隔离、管理硬件;所有硬件访问都要经过它。
  • Type 1 (bare-metal) e.g. VMware ESX — runs directly on hardware, high performance. Type 2 (hosted) e.g. VMware GSX — runs as an app on a host OS, for dev/test. Type 1(裸金属型)如 VMware ESX——直接跑在硬件上,性能高。Type 2(宿主型)如 VMware GSX——作为应用跑在宿主操作系统上,用于开发测试。
  • Xen: thin layer; Domain 0 = privileged VM handling I/O. KVM: turns the Linux kernel into a hypervisor; a guest runs as a host process. Xen:薄层;Domain 0 是处理 I/O 的特权虚拟机。KVM:把 Linux 内核变成 hypervisor,guest 作为宿主机的一个进程运行。

AWS Nitro 系统 真题 Q1 答案

  • Replaced Xen since 2017. Nitro Hypervisor — lightweight, purpose-built, HVM-based; only partitions/schedules CPU & memory. 2017 年起取代 Xen。Nitro Hypervisor——轻量、专门构建、基于 HVM;只负责 CPU 和内存的分区与调度。
  • Nitro Cards — offload networking (ENA, up to 100 Gbps), storage (EBS/NVMe), management, monitoring, security to hardware. Nitro 卡——把网络(ENA,最高 100 Gbps)、存储(EBS/NVMe)、管理、监控、安全卸载到专用硬件。
  • Security Chip — hardware root of trust; Domain 0 no longer needed. 安全芯片——硬件信任根;不再需要 Domain 0。
  • Bare-metal instances use Nitro cards but not the Nitro hypervisor. 裸金属实例使用 Nitro 卡,但用 Nitro hypervisor。
  • Benefits vs Xen: near bare-metal performance (offload); small attack surface (thin hypervisor, no Dom0). 相比 Xen 的优势:性能接近裸机(功能卸载到硬件);攻击面小(hypervisor 极薄、无 Dom0)。
例子 — 考试答题骨架 "The Nitro System has a thin HVM hypervisor that only manages CPU/memory; Nitro Cards offload networking, storage, security and monitoring to dedicated hardware; a Security Chip provides a hardware root of trust. Compared with Xen it gives near bare-metal performance and a smaller attack surface (no privileged Domain 0)." 译:Nitro 系统有一个薄的 HVM hypervisor,只管 CPU/内存;Nitro 卡把网络、存储、安全、监控卸载到专用硬件;安全芯片提供硬件信任根。相比 Xen,它性能接近裸机、攻击面更小(无特权 Domain 0)。

EC2 要点

  • 9-step launch: AMI → instance type → key pair → network → security group → storage → IAM role → user data → tags. 启动 9 步:AMI → 实例类型 → 密钥对 → 网络 → 安全组 → 存储 → IAM 角色 → 用户数据 → 标签。
  • Naming t3.large = family t, generation 3, size large. Categories: General/Compute/Memory/Storage/Accelerated. 命名 t3.large=家族 t、代际 3、规格 large。类别:通用/计算/内存/存储/加速。
  • Key pair: AWS stores the public key; you keep the private key (.pem). 密钥对:AWS 存公钥,你保留私钥(.pem)。
  • Lifecycle: only EBS-backed instances can stop/start; Instance Store-backed can only terminate. 生命周期:只有 EBS 型实例能 stop/start;实例存储型只能 terminate。

存储对比:EBS / 实例存储 / EFS

Item 项目Instance Store 实例存储EBSEFS
Persistence
持久性
Ephemeral, lost on stop/terminate
临时,停机/终止即丢
Persistent
持久
Persistent
持久
Attach 挂载Host physical disk
宿主机物理盘
Network-attached, single instance, single AZ
网络挂载,单实例,单 AZ
NFS, many instances (Linux)
NFS,多实例共享(Linux)
Move across AZ
跨 AZ 迁移
n/a
不适用
Snapshot→S3→new volume in target AZ
快照→S3→在目标 AZ 建新卷
Regional
区域级
Use case 用途Scratch/cache
临时/缓存
Boot + DB data
系统盘 + 数据库数据
Shared file system
共享文件系统
选择题陷阱:"sudden hardware failure, all batch data lost" → it was on Instance Store. "launch 50 identical instances" → create an AMI. "突发硬件故障、批处理数据全丢"=数据在实例存储上;"批量启动 50 个相同实例"=做一个 AMI

2 · S3 存储 Q1 + 概念

  • Object = key + metadata + content. Bucket name is globally unique and immutable. Flat structure; "folders" are key prefixes. 对象=键+元数据+内容。桶名全球唯一且不可改。扁平结构,"文件夹"只是键前缀。
  • Durability 11 nines; Standard stores across ≥3 AZs. Availability is separate (~99.99%). 持久性 11 个 9;Standard 跨 ≥3 个 AZ。可用性是另一个数(约 99.99%)。
  • Free: data IN + transfer within same region. Paid: storage, cross-region OUT, API requests. 免费:数据传入 + 同区域内传输。收费:存储量、跨区域传出、API 请求。
  • Storage classes: Standard / Intelligent-Tiering / Standard-IA (min 30d) / One Zone-IA (1 AZ) / Glacier Instant·Flexible·Deep Archive. 存储类:标准 / 智能分层 / 标准-IA(最少 30 天)/ 单区-IA(1 个 AZ)/ Glacier 即取·灵活·深度归档。
  • Lifecycle: Transition (change class) + Expiration (delete). 生命周期:Transition(转存储类)+ Expiration(到期删除)。

冗余 vs 版本控制 vs 复制 Q2/Q6

Item 项目Redundancy 冗余Versioning 版本控制Replication 复制(CRR/SRR)
Protects
防什么
hardware/AZ failure
硬件/AZ 故障
human error (overwrite/delete)
人为误操作(覆盖/删除)
region failure / compliance / latency
区域级故障/合规/延迟
How
怎么做
multi-AZ copies within region
region 内多 AZ 复制
multiple versions in same bucket
同桶保留多版本
copy to another bucket
复制到另一个桶
Cost 费用free, default
免费、默认
extra storage
额外存储费
needs versioning on both buckets
两个桶都要开版本控制
实例推演 — 版本控制 + CRR(真题 Q6) Bucket has versioning + CRR. Upload report.csv v1, then v2, then a delete without version ID. 桶开了版本控制 + CRR。上传 report.csv 的 v1,再传 v2,再做一次不带版本号的删除。 Source: v1, v2, and a delete marker (current). GET → 404; GET with v2 id → returns v2. 源桶:有 v1、v2 和一个删除标记(当前版本)。GET → 404;带 v2 版本号 GET → 返回 v2。 Destination: v1 & v2 replicated, but delete markers are NOT replicated by default → current is still v2 → GET → returns v2. 目标桶:复制了 v1、v2,但删除标记默认不复制 → 当前版本仍是 v2 → GET → 返回 v2。
要点:a delete marker = same key, own version ID + metadata. Deleting a specific version is also NOT replicated by default. 删除标记=同 key、有自己的版本 ID 和元数据。删除某个指定版本也默认不复制。

3 · RDS & Aurora 概念

Multi-AZ vs Read Replica Q3

Item 项目Multi-AZRead Replica 读副本
Replication
复制方式
synchronous
同步
asynchronous
异步
Purpose 用途HA + automatic failover
高可用 + 自动故障转移
read scaling
读扩展
Readable?
能否读
standby not readable
standby 不可读
readable; can be promoted
可读;可提升为主
Count 数量1 standby
1 个 standby
RDS up to 5; Aurora up to 15
RDS 最多 5;Aurora 最多 15

Aurora 架构

  • DB engine separated from a distributed storage layer. Each 10GB segment → 6 copies across 3 AZs (2 per AZ). Write quorum 4/6, read quorum 3/6. 数据库引擎与分布式存储层分离。每个 10GB 段 → 6 副本跨 3 个 AZ(每 AZ 两份)。写仲裁 4/6,读仲裁 3/6。
  • "Log is the Database": primary sends only redo log records (not data pages); durable once 4/6 nodes ack; storage nodes materialize pages independently. "日志即数据库":主库只发 redo 日志(不发数据页);4/6 节点确认即持久;存储节点独立把日志生成数据页。
实例 — 故障下的仲裁 • Lose 1 whole AZ (−2 copies) → 4 remain → meets write quorum 4/6 → writes continue. • 丢掉整个 AZ(少 2 份)→ 剩 4 份 → 满足写 4/6 → 写入继续。 • Lose 1 AZ + 1 extra node (−3) → 3 remain → meets read quorum 3/6 → reads OK, writes pause. • 丢 1 个 AZ + 再丢 1 个节点(少 3 份)→ 剩 3 份 → 满足读 3/6 → 读可以,写暂停。

LSN / VCL / CPL / VDL Q7

  • LSN log sequence number. VCL = highest LSN the volume is contiguously complete to. CPL = a transaction consistency point. VDL = highest CPL that is ≤ VCL; anything above VDL is truncated. LSN 日志序列号。VCL=卷连续完整到达的最高 LSN。CPL=事务一致性点。VDL=不超过 VCL 的最大 CPL(真正的持久点);高于 VDL 的日志被截断。
实例 — 计算 VDL Case A: VCL=1006, CPLs at 1003 & 1007 → 1007 > VCL excluded → VDL = 1003. 情况 A:VCL=1006,CPL 在 1003 和 1007 → 1007>VCL 排除 → VDL=1003 Case B: VCL=1050, CPLs at 900,1000,1100 → CPLs ≤1050 are 900 & 1000 → VDL = 1000, truncate 1001–1050. 情况 B:VCL=1050,CPL 在 900/1000/1100 → ≤1050 的是 900、1000 → VDL=1000,截断 1001–1050。

4 · IAM 身份 + 策略 Q2 + Q3 = 20 分

责任共担模型

AWS = security OF the cloud (hardware/virtualization/network). You = security IN the cloud (OS/app/SG/IAM/data). Authentication (who) → Authorization (what). AWS 负责"云本身的安全"(硬件/虚拟化/网络)。你负责"云之中的安全"(操作系统/应用/安全组/IAM/数据)。认证(你是谁)→ 授权(你能做什么)。

四种身份 Q2

Identity 身份What 是什么Notes 说明
User 用户person/app, long-term creds
人/应用,长期凭证
password (console) + access key/secret (programmatic)
密码(控制台)+ 访问密钥/秘密密钥(程序化)
Group 组set of users, shared policies
用户的集合,共享策略
cannot log in / nest / be assumed
不能登录/嵌套/被 assume
Policy 策略JSON permissions
JSON 权限
attached to user/group/role
附到 用户/组/角色
Role 角色temporary creds via STS
STS 发的临时凭证
key + secret + session token + expiry; assumed by users/apps/services
访问密钥+秘密密钥+会话令牌+过期时间;被用户/应用/服务 assume
EC2 访问 S3 最佳实践:attach a Role via an instance profile → app gets temporary, auto-rotated creds. Never hard-code access keys. 用 Instance Profile(实例配置文件)给实例附一个 Role → 应用拿到临时、自动轮换的凭证。绝不要硬编码访问密钥。

策略判定 Q3

Order: default Deny → if any explicit Deny → Deny → else explicit Allow → Allow, else implicit Deny. Explicit Deny > Allow > default Deny. 顺序:默认拒绝 → 若有任何显式 Deny → 拒绝 → 否则看显式 Allow → 有则允许,没有则隐式拒绝。显式 Deny > 显式 Allow > 默认拒绝。

ARN: arn:partition:service:region:account-id:resource. S3 needs two resource forms: arn:aws:s3:::bucket (bucket actions like ListBucket) + arn:aws:s3:::bucket/* (object actions like GetObject). ARN 结构如上。S3 资源要写两种:arn:aws:s3:::bucket(桶级操作如 ListBucket)+ arn:aws:s3:::bucket/*(对象级操作如 GetObject)。

实例 — 分析一段策略(Q3 题型)
{
  "Effect": "Allow",
  "Action": ["s3:GetObject","s3:PutObject","s3:DeleteObject"],
  "Resource": "arn:aws:s3:::comp5349-*/*",
  "Condition": {
    "StringEquals": {"aws:ResourceTag/Environment": "production"},
    "StringLike":   {"s3:prefix": "uploads/*"}
  }
}
Permits: Get/Put/Delete on objects (the /*) in any bucket named comp5349-*, only when bucket tag Environment=production AND key prefix is uploads/. 允许:对名字以 comp5349- 开头的桶里、uploads/ 前缀的对象(注意 /* 是对象级)做 Get/Put/Delete,且仅当桶有标签 Environment=production、且 key 前缀是 uploads/。 Forbids: ListBucket (not in Action + object-level resource), non-comp5349- buckets, non-production, keys outside uploads/, any other action. No explicit Deny → only matching requests succeed. 禁止/未授予:ListBucket(不在 Action 里、且资源是对象级)、非 comp5349- 的桶、非 production、非 uploads/ 前缀、其他任何操作。没有显式 Deny → 只有完全匹配条件的请求才成功,其余隐式拒绝。

身份策略 vs 资源策略 · RBAC vs ABAC

  • Identity-based (on user/group/role): "what I can access". Resource-based (S3 bucket policy / SQS queue policy): has a Principal = "who can access me". 身份策略(附在用户/组/角色上):"我能访问什么"。资源策略(S3 桶策略 / SQS 队列策略):带 Principal,"谁能访问我"。
  • RBAC lists explicit ARNs (grows with resources). ABAC uses tags in Conditions → new tagged resources auto-covered. RBAC 列具体 ARN(资源一多,策略维护爆炸)。ABAC 在 Condition 里用标签 → 新资源打上标签就自动纳入。
实例 — 企业联合登录流程 Employee → authenticate to corporate IdP (SAML) → IdP returns assertion → app calls STS AssumeRoleWithSAML → STS returns temporary creds mapped to a Role → access AWS. No IAM users created. 员工 → 登录企业身份提供方 IdP(SAML)→ IdP 返回断言 → 应用调用 STS 的 AssumeRoleWithSAML → STS 返回映射到某 Role 的临时凭证 → 访问 AWS。无需创建 IAM 用户。 (互联网/社交登录用 OIDC;面向终端用户的 B2C 应用用 Cognito:User Pool=用户目录/JWT,Identity Pool=临时凭证。)

5 · VPC / 子网 / 安全组 Q5 = 16 分

  • VPC: logically isolated network in one region, spanning AZs. Subnet lives in a single AZ. CIDR set at creation, immutable; max /16, min /28; subnet CIDRs can't overlap. VPC:单 region 内、跨 AZ 的逻辑隔离网络。子网在单个 AZ 内。CIDR 创建时定、不可改;最大 /16、最小 /28;子网 CIDR 不能重叠。
  • 5 reserved IPs per subnet (e.g. 10.0.1.0/24): .0 network, .1 VPC router, .2 DNS, .3 reserved, .255 broadcast. 每个子网保留 5 个 IP(以 10.0.1.0/24 为例):.0 网络地址、.1 VPC 路由器、.2 DNS、.3 预留、.255 广播。
  • Route table: the local route (VPC CIDR → local) lets subnets talk internally. Public subnet adds 0.0.0.0/0 → IGW; private adds 0.0.0.0/0 → NAT GW. 路由表:本地路由(VPC CIDR → local)让子网内部互通。公有子网加 0.0.0.0/0 → IGW;私有子网加 0.0.0.0/0 → NAT 网关
  • IGW: exactly one per VPC, HA. NAT Gateway: outbound only; a public NAT GW must be in a public subnet + have an EIP; one per AZ for HA. IGW(互联网网关):每个 VPC 正好一个,高可用。NAT 网关:只允许出站;公有 NAT 网关必须放在公有子网 + 绑一个弹性 IP;每 AZ 一个做高可用。
  • Security Group: stateful (return traffic auto-allowed), instance-level, allow-only. (NACL = stateless, subnet-level, allow+deny.) 安全组:有状态(返回流量自动放行)、实例级、只有允许规则。(NACL=无状态、子网级、有允许+拒绝。)
  • Best practice: use a SG as the source of another SG (not a CIDR) → precise, works across AZs as instances scale. 最佳实践:把一个安全组作为另一个安全组的"源"(而不是写 CIDR)→ 精确,且随实例扩缩在跨 AZ 时仍生效。
实例 — 三层 VPC 设计(Q5) VPC 10.0.0.0/16,跨 2 个 AZ。 • 子网:公有 10.0.0.0/2410.0.1.0/24;应用私有 10.0.2.0/2410.0.3.0/24;数据库私有 10.0.4.0/2410.0.5.0/24 • VPC 上挂 IGW;每 AZ 一个 NAT 网关放在公有子网(各绑 EIP)。 • 公有路由表:0.0.0.0/0→IGW。私有路由表:0.0.0.0/0→NAT • 安全组:ALB-SG ← 公网 80/443;Web-SG ← 来自 ALB-SG 的应用端口;App-SG ← 来自 Web-SG;DB-SG ← 只允许来自 App-SG 的 5432 请求路径:client → IGW → 公有路由表 → ALB(443) → web 实例(Web-SG 收 ALB-SG) → app(App-SG 收 Web-SG) → DB(DB-SG 5432 收 App-SG)。app/db 经 NAT 出网;DB 永不对公网开放。
CIDR 判断(lab13 Q5):VPC 172.31.0.0/16 覆盖 172.31.0.0–172.31.255.255 → 合法子网如 172.31.10.0/24;不合法:10.x、192.168.x、172.32.x。

6 · 自动伸缩 + ALB Q6 = 8 分

  • Scalability = handle growth; Elasticity = scale out AND in on demand. Vertical (scale up, has limits, downtime) vs Horizontal (scale out, add machines + LB). 可扩展性=应对增长;弹性=按需扩容也能缩容。垂直(向上升级,有上限、需停机)vs 水平(向外加机器 + 负载均衡)。
  • CloudWatch: metrics → Alarm → trigger ASG / SNS / EC2 action. CloudWatch:指标 → 告警 → 触发 ASG / SNS / EC2 操作。
  • ASG config: capacity (min/desired/max), launch template (AMI/type/SG/user-data — subnet is set on the ASG, not the template), load balancer, scaling policy. Policies: schedule-based; target tracking (CPU=60%); step; simple. ASG 配置:容量(min/desired/max)、启动模板(AMI/类型/SG/用户数据——子网在 ASG 上设,不在模板里)、负载均衡器、伸缩策略。策略:定时;目标跟踪(如 CPU=60%);步进;简单。
  • ALB (L7): Listener → Listener rules (forward/redirect/respond) → Target group (health checks). Algorithms: round-robin (default) or Least Outstanding Requests (good when request times vary). ALB(七层):监听器 → 监听规则(转发/重定向/响应) → 目标组(健康检查)。算法:轮询(默认) 或 最少未完成请求 LOR(请求耗时差异大时更好)。
实例 — ALB + ASG(min=2, max=5, 跨 2 AZ) ALB distributes across healthy targets in both AZs and health-checks them. ASG keeps 2–5 instances across the AZs. ALB 把请求分发到两个 AZ 里的健康目标并做健康检查。ASG 在两个 AZ 间维持 2–5 台实例。 HA: min=2 across 2 AZs → one instance/AZ can fail and still serve. 高可用:min=2 且跨 2 AZ → 一个实例或一个 AZ 故障仍能服务。 At CPU 80%: CloudWatch reports high CPU → ASG target-tracking launches new instances → auto-register with ALB target group → traffic spreads → CPU falls. CPU 80% 时:CloudWatch 报告高 CPU → ASG 目标跟踪启动新实例 → 自动注册到 ALB 目标组 → 流量分摊 → CPU 回落。
健康检查故障替换(7 步):目标组每 30s 检查 → 实例返回错误 → 标记不健康 → ALB 立即停止向它转发 → ASG 确认不健康 → 终止 → 按启动模板启新实例 → 注册到目标组 → 通过检查后恢复转发。

7 · SQS / SNS Q4 = 6 分

  • SQS = point-to-point, pull; one message → one consumer. Max 256KB. Standard (high throughput, at-least-once, best-effort order) vs FIFO (strict order, exactly-once). SQS=点对点、拉取;一条消息只给一个消费者。最大 256KB。标准队列(高吞吐、至少一次、尽力保序) vs FIFO(严格保序、恰好一次)。
  • Visibility timeout: after a consumer receives a message it is invisible to others for the timeout; consumer must DeleteMessage when done; if not, it becomes visible again (at-least-once). 可见性超时:消费者取走消息后,在超时时间内对其他消费者不可见;处理完必须 DeleteMessage;否则到期后重新可见(至少一次)。
  • DLQ: after exceeding maxReceiveCount, the failing message moves to a dead-letter queue for investigation. 死信队列 DLQ:超过 maxReceiveCount 后,反复失败的消息转入死信队列供排查。
  • SNS = pub/sub, push; one → many subscribers. Fan-out = SNS → multiple SQS queues, each consumed independently. SNS=发布/订阅、推送;一对多订阅者。扇出 Fan-out=SNS → 多个 SQS 队列,各自独立消费。
实例推演 — 可见性超时时序 超时=20s,2 个 worker。Worker A 在 t=0 取走 M1,处理需 25s。 • t=0–20s:M1 不可见 → B 去处理 M2/M3。 • t=20s:A 没处理完、也没删 M1 → M1 重新可见 → B 可能取走并重复处理 M1。 • t=25s:A 处理完想删,但 B 可能已在处理 → 重复消费 修复:把超时设得长于最大处理时间,或用 ChangeMessageVisibility 中途延长;并让处理幂等
跨服务权限:SNS→SQS 要生效,SQS 队列策略必须允许该 SNS 主题 sqs:SendMessage(资源策略,Principal=SNS)。

8 · 容器 & ECS Q1 选择 + Q4 题型

  • Container vs VM: a container shares the host kernel (namespace = isolated view; cgroup = resource limits) → lightweight. A VM runs a full guest OS via a hypervisor → heavier, stronger isolation. 容器 vs 虚拟机:容器共享宿主机内核(namespace=隔离视图;cgroup=限制资源) → 轻量。虚拟机经 hypervisor 跑完整 guest OS → 更重、隔离更强。
  • Docker: image (read-only layers) + container (thin writable top layer → ephemeral) + registry (AWS = ECR). Persistence: volume / bind mount / tmpfs. Docker:镜像(只读层) + 容器(顶层薄可写层 → 临时) + 仓库(AWS=ECR)。持久化:volume / bind mount / tmpfs。
  • Network modes: bridge (default, virtual bridge + NAT), host (no isolation), none, overlay (multi-host). 网络模式:bridge(默认,虚拟网桥+NAT)、host(无隔离)、none、overlay(跨主机)。

ECS

EC2 + ALBECS + ALB
config unit = Launch Template
配置单元 = 启动模板
config unit = Task Definition
配置单元 = 任务定义
count via ASG
数量靠 ASG
count via ECS Service
数量靠 ECS Service
app baked into AMI
应用打进 AMI
app = container image
应用 = 容器镜像
  • Dynamic port mapping: host port = 0 → ECS auto-assigns, ALB target group registers it → many copies per instance. 动态端口映射:host port=0 → ECS 自动分配,ALB 目标组注册 → 一台实例可跑多个副本。
  • Two scaling layers: tasks (ECS Service) + cluster capacity (EC2 ASG, or use Fargate). Service discovery via CloudMap / Service Connect / App Mesh. 两层扩缩:任务(ECS Service) + 集群容量(EC2 的 ASG,或用 Fargate 免管理)。服务发现:CloudMap / Service Connect / App Mesh。
实例 — 排查 ECS 任务反复失败 看任务的 stopped reason + 退出码 → CloudWatch 日志(程序崩溃?) → 镜像能否拉取(ECR 权限/标签) → 任务角色权限(S3/DynamoDB) → 健康检查/端口 → 是否 OOM(内存超限) → 环境变量/Secrets 注入。

9 · Serverless / Lambda Q1 选择

  • FaaS: stateless, event-driven, pay-per-use, auto-scaling. Max 900s; /tmp ephemeral. FaaS:无状态、事件驱动、按用付费、自动扩展。最长 900 秒;/tmp 临时。
  • Two permission types: resource-based policy = who can invoke; execution role = what the function can do (e.g. s3:GetObject). 两类权限:资源策略=谁能调用我;执行角色=函数能做什么(如 s3:GetObject)。
  • MicroVM (Firecracker, KVM-based): isolation between container and full VM — strong isolation, low overhead. 微VM(Firecracker,基于 KVM):隔离介于容器和完整 VM 之间——强隔离、低开销。
  • VPC: by default Lambda reaches S3/DynamoDB but not RDS in your VPC → put it in the VPC/subnet to reach private RDS. VPC:默认 Lambda 可达 S3/DynamoDB,但访问不到你 VPC 内的 RDS → 要把函数放进 VPC/子网才能访问私有 RDS。

反模式

  • Recursive trigger: S3 event → Lambda → writes back to same bucket → re-triggers → run-away cost. Fix: output to a different bucket/prefix or filter the trigger. 递归触发:S3 事件 → Lambda → 写回同一个桶 → 再次触发 → 费用失控。修复:输出到不同桶/前缀,或过滤触发条件。
  • Lambda calling Lambda (deep sync chain) → wasted cost + complex errors → use SQS/SNS or Step Functions. Lambda 调 Lambda(深度同步链) → 浪费费用 + 错误处理复杂 → 用 SQS/SNS 或 Step Functions。
  • Synchronous waiting on long ops → event-driven instead. Monolith → split into functions. 同步等待长操作 → 改事件驱动。单体函数 → 拆成多个函数。
实例 — API Gateway→Lambda vs ALB→EC2
Item 项目API GW → LambdaALB → EC2
Connect 连接invokes via service API
经服务 API 调用
forwards HTTP to a port
把 HTTP 转发到端口
Access control
访问控制
Lambda resource policy allows API GW
Lambda 资源策略允许 API GW 调用
EC2 SG allows ALB-SG
EC2 安全组允许来自 ALB-SG
Scaling 扩展auto per invocation
按调用自动扩展
ASG adds/removes EC2
ASG 增减 EC2
Idle cost
空闲成本
near zero
接近零
EC2 costs while running
EC2 运行就计费
Best for 适合spiky/low traffic, short tasks
突发/低流量、短任务
steady, long-running
稳定、长时间运行

10 · Kubernetes Q1 选择

  • Like an "OS for a cluster"; declarative with self-healing. Two planes: Control Plane (master) + Workload Plane (workers). 像"集群的操作系统";声明式、自愈。两个平面:控制平面(master) + 工作平面(worker)。
  • Control plane: API Server (single entry) · Scheduler (which worker) · Controller Manager (replication/failures) · etcd (cluster state; only API Server accesses). 控制平面:API Server(唯一入口) · Scheduler(pod 落哪个 worker) · Controller Manager(复制/故障处理) · etcd(集群状态;只有 API Server 能访问)。
  • Worker: kubelet (manages node containers) · kube-proxy (network rules) · container runtime. Worker 节点:kubelet(管理本节点容器) · kube-proxy(网络规则) · 容器运行时。
  • Pod: smallest scheduling unit; 1+ containers; same node; share network namespace (one pod IP, talk via loopback, can't bind same port); never spans nodes. Pod:最小调度单元;含 1+ 容器;同节点;共享网络命名空间(同一个 pod IP、可经 loopback 通信、不能绑同一端口);永不跨节点。
  • Deployment manages replicas; Service gives ephemeral pods a stable address + load balancing. Deployment 管理副本数;Service 给临时的 pod 一个稳定地址 + 负载均衡。
  • Grouping: Namespace (isolation) · Label (key-value, selectors match, like AWS tags) · Annotation (non-identifying info). 分组:Namespace(隔离) · Label(键值对,selector 用它匹配,类似 AWS tag) · Annotation(非标识信息)。
  • Sidecar: helper container in the same pod (e.g. log/content agent via shared volume). Sidecar:同 pod 内的辅助容器(如经共享卷收日志/送内容)。
实例 — Deployment + Service 清单(manifest)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels: { app: web }
  template:
    metadata:
      labels: { app: web }
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata: { name: web }
spec:
  selector: { app: web }
  ports:
  - port: 80
    targetPort: 80
四个必填字段:apiVersion / kind / metadata / spec。Service 的 selector 必须匹配 pod 模板的 labels
Concept 概念ECSKubernetes
deploy unit
部署单元
TaskPod
replica manager
副本管理
ECS ServiceDeployment
container config
容器配置
Task DefinitionPod template
Pod 模板
load balance
负载均衡
ALB target group
ALB 目标组
Service

11 · CloudFormation 概念

  • IaC; a template creates a stack. CFN itself is free. 8 sections — only Resources is mandatory. 基础设施即代码;一个模板创建一个栈(stack)。CFN 本身免费。8 个段——只有 Resources 必填。
  • Parameters (inputs) · Mappings (static lookup, classic = region→AMI) · Outputs (Export → cross-stack via Fn::ImportValue) · Conditions · Transform. Parameters(输入值) · Mappings(静态查找,经典=region→AMI) · Outputs(Export → 用 Fn::ImportValue 跨栈引用) · Conditions · Transform。
  • Functions: !Ref (physical ID/default), !GetAtt (an attribute), !Sub (string with vars), !FindInMap, !Select+!GetAZs. 函数:!Ref(物理 ID/默认值)、!GetAtt(取某属性)、!Sub(带变量的字符串)、!FindInMap!Select+!GetAZs
  • DependsOn: explicit creation order. On failure → automatic rollback. Preview updates with a Change Set. DependsOn:显式创建顺序。失败 → 自动回滚。用变更集(Change Set)预览更新。
实例 — !Ref vs !GetAtt 安全组报错(lab13) RDS with VPCSecurityGroups: [ !Ref MyDBSecurityGroup ] fails with "Invalid security group". RDS 写 VPCSecurityGroups: [ !Ref MyDBSecurityGroup ] 报错 "Invalid security group"。 Why: for an EC2 SecurityGroup, !Ref returns the group ID only if VpcId is set, otherwise the name — VPCSecurityGroups needs the ID. 原因:对 EC2 安全组,!Ref 只有在设了 VpcId 时才返回 ID,否则返回名字——而 VPCSecurityGroups 需要的是 ID。 Fix: VPCSecurityGroups: [ !GetAtt MyDBSecurityGroup.GroupId ]. 修复:改用 !GetAtt MyDBSecurityGroup.GroupId 取出 GroupId。
实例 — 最小模板片段
Resources:
  WebSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref VPC
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 80
        ToPort: 80
        CidrIp: 0.0.0.0/0
Outputs:
  SGId:
    Value: !GetAtt WebSG.GroupId
    Export: { Name: WebSGId }   # 跨栈引用

12 · Assignment 2 讨论 Q7 = 10 分

你的 A2 = 部署在 AWS 上的事件驱动 PDF RAG 对比应用。

  • Components: VPC (public/private subnets, 2 AZs) · IGW · NAT GW · Bastion · ALB → ASG web tier (EC2) · worker EC2 · S3 (PDFs) · RDS PostgreSQL · SNS · 2 SQS queues. 组件:VPC(公私子网,2 个 AZ) · IGW · NAT 网关 · 堡垒机 · ALB → ASG web 层(EC2) · worker EC2 · S3(存 PDF) · RDS PostgreSQL · SNS · 2 个 SQS 队列。
  • End-to-end flow: client → ALB → web → upload PDF to S3 → publish to SNS → SNS fans out to SQS → worker polls SQS → fetch PDF from S3 → run RAG comparison → write results to RDS → web reads RDS to display. Processed messages deleted; failures retry via visibility timeout → DLQ. 端到端流程:client → ALB → web 实例 → 上传 PDF 到 S3 → 发布到 SNS → SNS 扇出到 SQS → worker 拉取 SQS → 从 S3 取 PDF → 跑 RAG 对比 → 结果写入 RDS → web 读 RDS 展示给用户。处理完删消息;失败经可见性超时重试 → 进 DLQ。
  • Why SNS+SQS: decouple (web responds immediately), buffer bursts, scale workers independently, fan-out to multiple consumers, at-least-once + DLQ reliability. 为何用 SNS+SQS:解耦(web 即时响应)、缓冲突发、worker 独立扩展、扇出给多个消费者、至少一次投递 + DLQ 的可靠性。
  • Security: SG chain (ALB-SG → Web-SG → Worker/RDS-SG 5432 only from app/worker), private tier via NAT, admin via Bastion, least-privilege IAM roles via instance profiles. 安全:安全组链(ALB-SG → Web-SG → Worker/RDS-SG 的 5432 只收 app/worker)、私有层经 NAT 出网、管理走堡垒机、用 Instance Profile 的最小权限 IAM 角色。
A1 扣分教训 — 避免丢分:别用超大截图;图里要画出 VPC + IGW;要描述组件交互(谁调谁),不要只列服务清单;要写明具体配置(CIDR、端口、SG 的源、实例类型)。
实例 — 可提的改进/取舍 高可用:每 AZ 一个 NAT、ALB 多 AZ、考虑 RDS Multi-AZ。扩展:worker 层也加 ASG(按 SQS 队列深度)或用 Fargate。成本:NAT 和常驻 EC2/RDS 空闲也花钱(可考虑 Lambda/Spot)。安全:用 SG 引用而非 CIDR、开加密(S3 SSE/RDS/TLS)、用 VPC 端点让 S3/RDS 流量不走公网。