feat: add infrastructure interview questions

Add comprehensive interview materials for:
- Service Mesh (Istio, Linkerd)
- RPC Framework (Dubbo, gRPC)
- Container Orchestration (Kubernetes)
- CI/CD (Jenkins, GitLab CI, GitHub Actions)
- Observability (Monitoring, Logging, Tracing)

Each file includes:
- 5-10 core questions
- Detailed standard answers
- Code examples
- Real-world project experience
- Alibaba P7 bonus points

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
yasinshaw
2026-03-01 00:06:28 +08:00
parent e10105c54a
commit d80d1cf553
5 changed files with 4887 additions and 0 deletions

1338
questions/ci-cd.md Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1179
questions/observability.md Normal file

File diff suppressed because it is too large Load Diff

745
questions/rpc-framework.md Normal file
View File

@@ -0,0 +1,745 @@
# RPC 框架
## 问题
**背景**在分布式系统中服务间通信需要高效、可靠的远程调用机制。RPCRemote Procedure Call框架屏蔽了网络通信的复杂性使远程调用像本地调用一样简单。
**问题**
1. 什么是 RPC它和 HTTP REST 有什么区别?
2. Dubbo 的核心架构和工作原理是什么?
3. gRPC 的优势是什么?它如何实现高性能?
4. 请描述 Dubbo 的负载均衡策略
5. Dubbo 的服务注册与发现机制是怎样的?
6. RPC 框架如何实现序列化?常见的序列化协议有哪些?
7. 在实际项目中如何选择 RPC 框架?
8. RPC 框架如何处理超时、重试和熔断?
---
## 标准答案
### 1. RPC vs HTTP REST
#### **RPC 定义**
远程过程调用Remote Procedure Call是一种计算机通信协议允许运行在一台计算机的程序调用另一台计算机的子程序而开发者无需额外编码这种交互。
#### **对比表**
| 特性 | RPC (Dubbo/gRPC) | HTTP REST |
|------|------------------|-----------|
| 传输协议 | TCP (长连接) | HTTP/1.1 (短连接) / HTTP/2 |
| 序列化 | 二进制Hessian/Protobuf | JSON/XML |
| 性能 | 高(紧凑、高效) | 中(文本解析开销) |
| 易用性 | 需要接口定义 | 无需定义,浏览器直接访问 |
| 耦合度 | 强耦合(需要 stub 代码) | 松耦合 |
| 流量管理 | 需要网关 | 天然支持Nginx等 |
| 适用场景 | 内部微服务通信 | 对外 API、跨语言调用 |
#### **代码对比**
**RPC 调用Dubbo**
```java
// 服务提供者
public interface UserService {
User getUserById(Long id);
}
// 服务消费者
// 像调用本地方法一样调用远程服务
@Reference
private UserService userService;
public void process() {
User user = userService.getUserById(1L);
}
```
**HTTP REST 调用**
```java
// 服务提供者
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getById(id);
}
}
// 服务消费者
RestTemplate restTemplate = new RestTemplate();
public void process() {
String url = "http://user-service/api/users/1";
User user = restTemplate.getForObject(url, User.class);
}
```
---
### 2. Dubbo 核心架构
#### **架构图**
```
┌─────────────────┐
│ Registry │
│ (注册中心) │
│ Zookeeper/Nacos│
└─────────────────┘
▲ ▲
│ │
Register │ │ Subscribe
(注册) │ │ (订阅)
│ │
┌──────────────────────┴───┴──────────────────────┐
│ │
│ Provider Consumer │
│ ┌──────────┐ ┌──────────┐│
│ │Protocol │ │Protocol ││
│ │ (协议层) │ │ (协议层) ││
│ └──────────┘ └──────────┘│
│ ┌──────────┐ ┌──────────┐│
│ │ Cluster │◄──────────────────►│ Cluster ││
│ │ (集群层) │ Directory │ (集群层) ││
│ └──────────┘ └──────────┘│
│ ┌──────────┐ ┌──────────┐│
│ │ Proxy │ │ Proxy ││
│ │ (代理层) │ │ (代理层) ││
│ └──────────┘ └──────────┘│
│ ┌──────────┐ ┌──────────┐│
│ │ Service │ │ Service ││
│ │ (服务层) │ │ (服务层) ││
│ └──────────┘ └──────────┘│
└─────────────────────────────────────────────┘
│ Invoke
│ (调用)
┌──────────┐
│ Channel │
│ (网络层) │
└──────────┘
│ Exchange
│ (数据交换)
┌──────────┐
│ Serialize│
│ (序列化) │
└──────────┘
```
#### **核心角色**
**1. Container服务容器**
- 负责启动、加载和运行服务提供者
- 通常是 Spring 容器
**2. Provider服务提供者**
- 暴露服务的应用
- 启动时向注册中心注册服务
**3. Consumer服务消费者**
- 调用远程服务的应用
- 启动时向注册中心订阅服务
**4. Registry注册中心**
- 服务注册与发现
- 常见实现Zookeeper、Nacos、Redis
**5. Monitor监控中心**
- 统计服务调用次数和调用时间
- 常见实现Dubbo Admin、Prometheus
#### **代码示例**
**服务提供者配置**
```xml
<!-- provider.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://dubbo.apache.org/schema/dubbo
http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!-- 提供方应用信息 -->
<dubbo:application name="user-provider"/>
<!-- 使用 Zookeeper 注册中心 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<!-- 使用 dubbo 协议暴露服务 -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- 声明需要暴露的服务接口 -->
<dubbo:service interface="com.example.UserService"
ref="userService" version="1.0.0"/>
<!-- 服务实现 -->
<bean id="userService" class="com.example.UserServiceImpl"/>
</beans>
```
**服务消费者配置**
```xml
<!-- consumer.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://dubbo.apache.org/schema/dubbo
http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!-- 消费方应用信息 -->
<dubbo:application name="user-consumer"/>
<!-- 使用 Zookeeper 注册中心 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<!-- 生成远程服务代理 -->
<dubbo:reference id="userService"
interface="com.example.UserService"
version="1.0.0"
timeout="3000"
retries="2"/>
</beans>
```
---
### 3. gRPC 高性能原理
#### **核心特性**
**1. HTTP/2 多路复用**
```
HTTP/1.1:
Request 1 ──► TCP Connection 1 ──► Response 1
Request 2 ──► TCP Connection 2 ──► Response 2
Request 3 ──► TCP Connection 3 ──► Response 3
HTTP/2:
Request 1 ──┐
Request 2 ──┼─► TCP Connection ──► Response 1
Request 3 ──┘ Response 2
Response 3
```
**2. Protobuf 二进制序列化**
```protobuf
// user.proto
syntax = "proto3";
package user;
service UserService {
rpc GetUser(GetUserRequest) returns (User);
rpc ListUsers(ListUsersRequest) returns (ListUsersResponse);
}
message User {
int64 id = 1;
string name = 2;
string email = 3;
}
message GetUserRequest {
int64 id = 1;
}
message ListUsersRequest {
int32 page = 1;
int32 size = 2;
}
message ListUsersResponse {
repeated User users = 1;
int32 total = 2;
}
```
**性能对比**
```
JSON: {"id":1,"name":"Alice","email":"alice@example.com"}
└─ 56 字节
Protobuf: [0x08 0x01 0x12 0x05 0x41 0x6C 0x69 0x63 0x65 ...]
└─ ~20 字节(压缩 60%+
```
**3. 流式传输**
```python
# 服务端流式 RPC
async def ListUsers(request, context):
for user in database.iter_users():
yield user # 持续发送,无需等待全部数据
# 客户端流式 RPC
async def UploadUsers(request_iterator, context):
for user_request in request_iterator:
database.save(user_request.user)
return UploadStatus(success=True)
# 双向流式 RPC
async def Chat(request_iterator, context):
async for msg in request_iterator:
response = process_message(msg)
yield response
```
#### **代码示例Python**
**服务端**
```python
import grpc
from concurrent import futures
import user_pb2
import user_pb2_grpc
class UserServiceImpl(user_pb2_grpc.UserServiceServicer):
def GetUser(self, request, context):
# 查询数据库
user = db.query(User).filter_by(id=request.id).first()
return user_pb2.User(
id=user.id,
name=user.name,
email=user.email
)
def ListUsers(self, request, context):
# 服务端流式响应
users = db.query(User).limit(request.size).offset(request.page * request.size)
for user in users:
yield user_pb2.User(id=user.id, name=user.name, email=user.email)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
user_pb2_grpc.add_UserServiceServicer_to_server(UserServiceImpl(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
if __name__ == '__main__':
serve()
```
**客户端**
```python
import grpc
import user_pb2
import user_pb2_grpc
def run():
with grpc.insecure_channel('localhost:50051') as channel:
stub = user_pb2_grpc.UserServiceStub(channel)
# 简单 RPC
response = stub.GetUser(user_pb2.GetUserRequest(id=1))
print(f"User: {response.name}")
# 服务端流式 RPC
for user in stub.ListUsers(user_pb2.ListUsersRequest(page=0, size=10)):
print(f"User: {user.name}")
if __name__ == '__main__':
run()
```
---
### 4. Dubbo 负载均衡策略
#### **策略对比**
| 策略 | 说明 | 适用场景 |
|------|------|----------|
| Random随机 | 随机选择 provider | 性能相近的实例 |
| RoundRobin轮询 | 按权重轮询 | 性能有差异的实例 |
| LeastActive最少活跃 | 优先调用活跃数少的 | 性能差异大 |
| ConsistentHash一致性哈希 | 相同参数路由到同一 provider | 有状态服务 |
| ShortestResponse最短响应 | 优先选择响应时间短的 | 对延迟敏感 |
#### **代码示例**
**配置负载均衡**
```xml
<dubbo:reference id="userService"
interface="com.example.UserService"
loadbalance="roundRobin" <!-- -->
timeout="3000"/>
```
**自定义负载均衡**
```java
public class CustomLoadBalance extends AbstractLoadBalance {
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// 自定义负载均衡逻辑
// 例如:基于地理位置的负载均衡
String location = getUserLocation();
return invokers.stream()
.filter(invoker -> invoker.getUrl().getParameter("location").equals(location))
.findFirst()
.orElse(invokers.get(0));
}
}
// 注册自定义负载均衡
SPI.register(CustomLoadBalance.class);
```
#### **LeastActive 原理**
```
Provider A: Active = 5 (正在处理 5 个请求)
Provider B: Active = 2 (正在处理 2 个请求)
Provider C: Active = 8 (正在处理 8 个请求)
选择顺序B > A > C
原因B 的负载最轻,应该优先分配
```
---
### 5. 服务注册与发现
#### **Zookeeper 实现**
**目录结构**
```
/dubbo
└─ com.example.UserService
├─ providers
│ ├─ dubbo://192.168.1.10:20880/...?version=1.0.0
│ ├─ dubbo://192.168.1.11:20880/...?version=1.0.0
│ └─ dubbo://192.168.1.12:20880/...?version=1.0.0
└─ consumers
└─ consumer://192.168.1.20/...?version=1.0.0
```
**工作流程**
```
1. Provider 启动
2. 创建临时节点 /dubbo/.../providers/dubbo://ip:port/...
3. Consumer 启动
4. 订阅 /dubbo/.../providers/ 节点
5. 获取 provider 列表
6. 监听 provider 变化(新增/下线)
7. 动态更新本地缓存
```
#### **代码示例Zookeeper**
```java
// 注册中心配置
RegistryConfig registry = new RegistryConfig();
registry.setAddress("zookeeper://127.0.0.1:2181");
registry.setTimeout(5000);
// 或者使用 Nacos
RegistryConfig registry = new RegistryConfig();
registry.setAddress("nacos://127.0.0.1:8848");
```
#### **服务健康检查**
```java
// Dubbo 心跳机制
public class HeartbeatTask implements Runnable {
@Override
public void run() {
// 每隔 5 秒发送心跳
channel.send heartbeat();
}
}
// Zookeeper 临时节点特性
// - Provider 断开连接后,临时节点自动删除
// - Consumer 立即感知到下线,剔除该 provider
```
---
### 6. 序列化协议对比
#### **常见序列化协议**
| 协议 | 优点 | 缺点 | 适用场景 |
|------|------|------|----------|
| Hessian | 简单、高效 | 不支持跨语言 | Dubbo 默认 |
| Protobuf | 高性能、跨语言 | 需要定义 .proto | gRPC |
| JSON | 易读、跨语言 | 冗长、解析慢 | HTTP REST |
| Kryo | 高性能 | 不支持跨语言 | Dubbo |
| Avro | 动态 schema、跨语言 | 性能略低 | Hadoop 生态 |
| FST | 高性能、兼容 JDK | 不支持跨语言 | Dubbo |
#### **性能对比**
```
序列化性能排名(从快到慢):
Kryo > FST > Protobuf > Hessian > Avro > JSON
序列化后大小排名(从小到大):
Protobuf ≈ Kryo < Hessian < Avro < JSON
```
#### **代码示例Protobuf**
```protobuf
// user.proto
syntax = "proto3";
message User {
int64 id = 1;
string name = 2;
string email = 3;
repeated string tags = 4;
}
```
```bash
# 编译 Protobuf
protoc --python_out=. user.proto
```
```python
# Python 序列化
import user_pb2
user = user_pb2.User()
user.id = 1
user.name = "Alice"
user.email = "alice@example.com"
user.tags.extend(["vip", "active"])
# 序列化
serialized = user.SerializeToString() # 二进制数据
# 反序列化
user2 = user_pb2.User()
user2.ParseFromString(serialized)
```
---
### 7. RPC 框架选型
#### **选型决策树**
```
是否需要跨语言调用?
├─ 是 → gRPCProtobuf 跨语言支持最好)
└─ 否 → 继续判断
是否需要高性能?
├─ 是 → DubboTCP 长连接、Hessian 序列化)
└─ 否 → 继续判断
是否需要简单易用?
├─ 是 → Spring Cloud OpenFeign基于 HTTP REST
└─ 否 → Dubbo
已有技术栈?
├─ Spring Cloud → OpenFeign/Dubbo
├─ Kubernetes → gRPC服务网格友好
└─ Dubbo → 继续使用 Dubbo
```
#### **实际项目经验**
**场景 1电商内部服务**
```
选择Dubbo
原因:
- 内部服务,都是 Java 技术栈
- 对性能要求高(高并发下单)
- 需要负载均衡、熔断降级
配置:
- 使用 Hessian 序列化
- Zookeeper 注册中心
- LeastActive 负载均衡
```
**场景 2跨语言微服务**
```
选择gRPC
原因:
- 后端 Java数据分析 PythonAI 服务 Go
- 需要统一的服务间通信协议
- Protobuf 高性能且跨语言
配置:
- Protobuf 定义接口
- HTTP/2 传输
- 多语言代码生成
```
---
### 8. 超时、重试和熔断
#### **超时配置**
```xml
<!-- Dubbo 超时 -->
<dubbo:reference id="userService"
interface="com.example.UserService"
timeout="3000"/> <!-- 3 秒超时 -->
<!-- 方法级超时 -->
<dubbo:reference id="userService"
interface="com.example.UserService">
<dubbo:method name="getUserById" timeout="1000"/>
<dubbo:method name="listUsers" timeout="5000"/>
</dubbo:reference>
```
#### **重试机制**
```xml
<dubbo:reference id="userService"
interface="com.example.UserService"
retries="2"/> <!-- 失败后重试 2 次 -->
<!-- 工作流程 -->
第一次调用 → 失败
第二次调用 → 失败
第三次调用 → 成功/失败
```
**注意**:幂等性操作才能重试(如查询),非幂等操作(如下单)不能重试
```xml
<!-- 非幂等操作禁用重试 -->
<dubbo:method name="createOrder" retries="0"/>
```
#### **熔断降级Dubbo**
```java
// 使用 Sentinel 实现熔断
@SentinelResource(value = "getUserById",
blockHandler = "handleBlock",
fallback = "handleFallback")
public User getUserById(Long id) {
return userService.getUserById(id);
}
// 熔断处理
public User handleBlock(Long id, BlockException ex) {
// 熔断时返回默认值
return new User(-1L, "Default", "default@example.com");
}
// 降级处理
public User handleFallback(Long id, Throwable ex) {
// 异常时返回降级数据
return new User(-1L, "Fallback", "fallback@example.com");
}
```
**熔断规则配置**
```java
// Sentinel 熔断规则
List<DegradeRule> rules = new ArrayList<>();
DegradeRule rule = new DegradeRule();
rule.setResource("getUserById");
rule.setGrade(RuleConstant.DEGRADE_GRADE_RT); // 平均响应时间
rule.setCount(100); // 100ms
rule.setTimeWindow(10); // 10 秒熔断时间
rules.add(rule);
DegradeRuleManager.loadRules(rules);
```
---
### 9. 实际项目经验
#### **场景 1订单系统性能优化**
```
问题订单创建接口延迟高2 秒)
排查:
1. 调用链追踪发现库存服务耗时最长
2. 库存服务使用 HTTP RESTJSON 序列化慢
3. 每次调用都建立新连接
解决:
1. 将库存服务从 HTTP REST 迁移到 Dubbo
2. 使用 Hessian 序列化
3. 启用长连接复用
4. 配置 LeastActive 负载均衡
结果:延迟降低到 300ms提升 85%
```
#### **场景 2服务注册中心故障**
```
问题Zookeeper 集群故障,服务调用失败
排查:
Consumer 每次调用都查询注册中心,导致无法发现服务
解决:
1. Dubbo 默认会缓存 provider 列表到本地
2. 配置缓存策略
<dubbo:registry address="zookeeper://127.0.0.1:2181"
file="${user.home}/output/dubbo.cache"/>
3. 注册中心故障时,使用本地缓存
结果:注册中心故障不影响已有服务调用
```
#### **场景 3序列化兼容性问题**
```
问题:升级服务版本后,旧客户端调用失败
原因:
- 新增字段使用了不可序列化的类型
- 客户端版本不兼容
解决:
1. Protobuf 默认兼容(新增字段不影响)
2. Hessian 需要保证序列化 ID 一致
3. 使用版本号区分服务
<dubbo:service interface="..." version="1.0.0"/>
<dubbo:service interface="..." version="2.0.0"/>
4. 灰度升级,逐步切换流量
结果:平滑升级,零停机
```
---
### 10. 阿里 P7 加分项
**架构设计能力**
- 设计过大规模 RPC 框架的集群架构(百万级 QPS
- 有自定义 RPC 框架开发经验
- 实现过服务网格与传统 RPC 框架的融合
**深度理解**
- 熟悉 Dubbo 源码SPI 机制、代理设计、集群容错)
- 理解 gRPC 的 HTTP/2 和 Protobuf 底层原理
- 有序列化协议的选型和优化经验
**性能调优**
- 优化过 TCP 参数连接池、KeepAlive、缓冲区大小
- 调整过 JVM 参数减少 GC减少对象创建、使用堆外内存
- 优化过网络参数MTU、TCP_NODELAY
**生产实践**
- 解决过 TCP 粘包/拆包问题
- 处理过序列化安全漏洞(如 Hessian 反序列化 RCE
- 实现过服务优雅上下线(注册预热、优雅停机)
**可观测性**
- 集成过分布式追踪SkyWalking、Jaeger
- 实现过 RPC 调用链路监控
- 设计过服务性能指标大盘QPS、延迟、成功率
**跨语言调用**
- 有 gRPC 多语言实现经验Java、Go、Python
- 解决过 Protobuf 跨语言兼容性问题
- 实现过动态代理生成(如 Python 调用 Java 服务)

605
questions/service-mesh.md Normal file
View File

@@ -0,0 +1,605 @@
# 服务网格 (Service Mesh)
## 问题
**背景**:在微服务架构中,随着服务数量增加,服务间的通信管理变得复杂。服务网格作为基础设施层,负责处理服务间通信的流量管理、安全性和可观测性。
**问题**
1. 什么是服务网格?它解决了哪些问题?
2. Istio 的核心组件有哪些?它们是如何协作的?
3. Sidecar 模式的优缺点是什么?
4. 请描述 Istio 的流量管理功能(灰度发布、蓝绿部署、熔断降级)
5. Istio 如何实现 mTLS双向 TLS
6. 在生产环境中使用服务网格遇到过哪些坑?
7. Linkerd 和 Istio 的区别是什么?如何选择?
---
## 标准答案
### 1. 服务网格概述
**定义**
服务网格是微服务架构中用于处理服务间通信的基础设施层,通常以轻量级网络代理的形式实现。
**核心功能**
- **流量管理**:路由规则、负载均衡、灰度发布
- **安全性**mTLS、JWT 验证、访问控制
- **可观测性**Metrics、Tracing、Logging
**解决的问题**
```
传统微服务架构的痛点:
├─ 服务间通信逻辑散落在每个服务中
├─ 熔断、重试、超时等逻辑重复实现
├─ 安全策略难以统一管理
├─ 可观测性数据收集困难
└─ 灰度发布、流量染色需要大量代码
服务网格的解决方案:
├─ 将通信逻辑下沉到 Sidecar 代理
├─ 控制平面统一配置管理
├─ 数据平面透明代理流量
├─ 自动收集可观测性数据
└─ 声明式 API 管理流量
```
---
### 2. Istio 核心组件
#### **架构图**
```
┌─────────────────┐
│ Control Plane │
└─────────────────┘
┌─────────────────┼─────────────────┐
│ │ │
┌─────────┐ ┌──────────┐ ┌──────────┐
│ Istiod │ │Pilot │ │Citadel │
│ (统一) │ │(流量管理) │ │(证书管理)│
└─────────┘ └──────────┘ └──────────┘
│ 配置下发
┌─────────────────────────────────────┐
│ Data Plane │
├─────────────────────────────────────┤
│ │
│ Service A Service B │
│ ┌─────────┐ ┌─────────┐ │
│ │ Envoy │◄────►│ Envoy │ │
│ │ Sidecar │ │ Sidecar │ │
│ └─────────┘ └─────────┘ │
│ │
└─────────────────────────────────────┘
```
#### **核心组件详解**
**1. Istiod统一控制平面**
- **Pilot**:流量管理和配置下发
- **Citadel**:证书管理和身份认证
- **Galley**配置验证和注入Istio 1.13+ 已合并到 Istiod
**代码示例 - Istiod 配置**
```yaml
# istiod deployment
apiVersion: v1
kind: Deployment
metadata:
name: istiod
namespace: istio-system
spec:
template:
spec:
containers:
- name: discovery
image: gcr.io/istio-testing/pilot:1.19.0
args:
- "discovery"
- "--monitoringAddr=:15014"
- "--log_output_level=default:info"
ports:
- containerPort: 15012 # Pilot 服务的 xDS 端口
name: grpc-xds
```
**2. Envoy Sidecar数据平面**
- 拦截所有进出流量
- 执行流量规则(路由、负载均衡)
- 收集 Metrics 和 Traces
- 处理 mTLS 加解密
**Sidecar 注入示例**
```yaml
# 自动注入 Sidecar
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
annotations:
sidecar.istio.io/inject: "true" # 启用自动注入
spec:
template:
metadata:
annotations:
sidecar.istio.io/rewriteAppHTTPProbers: "true" # 重写 HTTP probes
spec:
containers:
- name: app
image: my-app:1.0.0
ports:
- containerPort: 8080
```
---
### 3. Sidecar 模式
#### **优点**
1. **透明性**:业务代码无感知,无需修改
2. **语言无关**:任何语言都能使用
3. **统一管理**:集中配置,易于维护
4. **渐进式采用**:可以逐步迁移
#### **缺点**
1. **资源开销**:每个服务都有 Sidecar增加内存和 CPU
```
典型资源占用:
- 内存50-100MB per Sidecar
- CPU5-10% per core
- 延迟增加1-5ms
```
2. **网络链路增加**
```
请求路径(有 Sidecar
Client → Sidecar A → Service A → Sidecar B → Service B
请求路径(无 Sidecar
Client → Service A → Service B
```
3. **调试复杂度**:多了一层网络代理
#### **优化方案**
```yaml
# Sidecar 资源限制
apiVersion: v1
kind: Pod
metadata:
name: my-app
spec:
containers:
- name: istio-proxy
resources:
requests:
cpu: 50m
memory: 64Mi
limits:
cpu: 500m
memory: 256Mi
```
**Sidecar 资源配置模式**
```yaml
# sidecar resources customization
apiVersion: v1
kind: ConfigMap
metadata:
name: istio-sidecar-injector
data:
values: |
sidecarResources:
requests:
cpu: 50m
memory: 64Mi
limits:
cpu: 500m
memory: 256Mi
```
---
### 4. 流量管理
#### **4.1 灰度发布 (Canary Deployment)**
**场景**:新版本 v2 发布给 10% 的流量
```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews
spec:
hosts:
- reviews
http:
- match:
- headers:
x-canary:
exact: "true" # 带特定 header 的流量走 v2
route:
- destination:
host: reviews
subset: v2
- route:
- destination:
host: reviews
subset: v1
weight: 90 # 90% 流量走 v1
- destination:
host: reviews
subset: v2
weight: 10 # 10% 流量走 v2
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: reviews
spec:
host: reviews
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
```
#### **4.2 蓝绿部署 (Blue-Green Deployment)**
**场景**:一键切换全部流量到新版本
```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: my-app
spec:
hosts:
- my-app
http:
- route:
- destination:
host: my-app
subset: blue # 所有流量指向 blue
weight: 100
# 切换到 green修改 subset 为 green
---
# Kubernetes Deployment同时存在 blue 和 green
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app-blue
spec:
template:
metadata:
labels:
version: blue
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app-green
spec:
template:
metadata:
labels:
version: green
```
#### **4.3 熔断降级 (Circuit Breaker)**
**场景**:防止故障扩散
```yaml
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: httpbin
spec:
host: httpbin
trafficPolicy:
connectionPool:
tcp:
maxConnections: 10 # 最大连接数
http:
http1MaxPendingRequests: 50 # 最大等待请求数
http2MaxRequests: 100 # 最大并发请求数
maxRequestsPerConnection: 2 # 每连接最大请求数
maxRetries: 3 # 最大重试次数
outlierDetection:
consecutiveErrors: 5 # 连续 5 次错误
interval: 30s # 每 30s 检查一次
baseEjectionTime: 30s # 最小熔断时间
maxEjectionPercent: 50 # 最多熔断 50% 的实例
minHealthPercent: 40 # 最小健康实例比例
```
**熔断状态图**
```
Closed → Open → Half-Open → Closed
↑ │ │
└────────┴──────────┘
```
#### **4.4 超时和重试**
```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews
spec:
hosts:
- reviews
http:
- retry:
attempts: 3 # 最多重试 3 次
perTryTimeout: 2s # 每次重试超时 2s
retryOn: 5xx,connect-failure,refused-stream # 重试条件
timeout: 10s # 总超时时间
route:
- destination:
host: reviews
```
---
### 5. mTLS (双向 TLS) 实现
#### **原理**
```
Service A Service B
│ │
│ 1. 发送连接请求(无证书) │
│ ─────────────────────────────────────►│
│ │
│ 2. 返回服务器证书 │
│ ◄─────────────────────────────────────│
│ │
│ 3. 发送客户端证书 │
│ ─────────────────────────────────────►│
│ │
│ 4. 验证通过,建立加密连接 │
│ ◄────────────────────────────────────►│
│ │
│ 5. 加密通信 │
│ ◄──────────────► │
```
#### **配置示例**
**全局启用 mTLS**
```yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: istio-system
spec:
mtls:
mode: STRICT # 严格模式:必须使用 mTLS
```
**按服务配置**
```yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: my-app-mtls
namespace: default
spec:
selector:
matchLabels:
app: my-app
mtls:
mode: PERMISSIVE # 宽松模式:兼容 mTLS 和明文
```
**服务授权**
```yaml
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: my-app-authz
spec:
selector:
matchLabels:
app: my-app
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/default/sa/frontend"] # 只允许 frontend SA 访问
to:
- operation:
methods: ["GET", "POST"]
```
#### **证书管理流程**
```
1. Citadel 工作负载证书
2. 证书存储在 Secret 中
3. Envoy Sidecar 启动时加载证书
4. 定期轮换证书(默认 24 小时)
5. 旧证书过期,使用新证书
```
---
### 6. 生产环境踩坑经验
#### **坑 1Sidecar 资源占用过高**
```yaml
# 问题100 个服务 × 100MB = 10GB 内存
# 解决:按需启用 Sidecar
apiVersion: v1
kind: Pod
metadata:
name: my-app
annotations:
sidecar.istio.io/inject: "false" # 禁用 Sidecar
```
#### **坑 2网络延迟增加**
```
问题:请求延迟从 5ms 增加到 10ms
原因:
- Sidecar 增加了一跳
- mTLS 加解密开销
解决:
1. 调整 Envoy 配置,减少日志级别
2. 使用 PERMISSIVE 模式降级
3. 增加超时时间配置
```
#### **坑 3配置下发延迟**
```yaml
# 问题:修改 VirtualService 后,流量未立即切换
# 原因Pilot 下发配置有延迟(默认 1s
# 解决:减少配置刷新间隔
apiVersion: v1
kind: ConfigMap
metadata:
name: istio
namespace: istio-system
data:
mesh: |-
defaultConfig:
proxyStatsMatcher:
inclusionRegexps:
- ".*" # 收集所有指标
discoveryRefreshDelay: 1s # 配置刷新延迟
```
```
#### **坑 4大规模性能问题**
```
问题:集群 1000+ 服务时Istiod 性能瓶颈
解决:
1. 部署多个 Istiod 实例
2. 使用 Namespace 隔离配置
3. 启用配置压缩
```
**多实例部署**
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: istiod
spec:
replicas: 3 # 多副本
```
---
### 7. Linkerd vs Istio
#### **对比表**
| 特性 | Linkerd 2.x | Istio |
|------|-------------|-------|
| 代理 | Rust 实现Linkerd2-proxy | EnvoyC++ |
| 性能 | 更低资源占用 | 资源占用较高 |
| 功能 | 聚焦核心功能 | 功能更丰富 |
| 集成 | Kubernetes 原生 | 支持多平台 |
| 学习曲线 | 简单 | 复杂 |
| 社区 | CNCF 毕业项目 | CNCF 孵化中 |
| 多集群支持 | 弱 | 强 |
| 流量管理 | 基础 | 高级(灰度、蓝绿等) |
#### **选择建议**
**选择 Linkerd**
- Kubernetes 原生环境
- 重视性能和资源占用
- 需要简单易用的解决方案
- 功能要求不高
**选择 Istio**
- 需要高级流量管理
- 多集群/多云环境
- 需要细粒度的安全控制
- 团队有运维能力
---
### 8. 实际项目经验
#### **场景 1电商系统灰度发布**
```
需求:新支付系统先给 5% 用户试用
方案:
1. 部署 payment-v2
2. 配置 VirtualService5% 流量走 v2
3. 监控错误率和延迟
4. 逐步增加流量比例5% → 20% → 50% → 100%
5. 出现问题立即回滚
```
#### **场景 2金融系统 mTLS 合规**
```
需求:所有服务间通信必须加密
方案:
1. 启用 STRICT mTLS 模式
2. 配置 AuthorizationPolicy只允许合法的 SA 访问
3. 定期轮换证书24 小时)
4. 审计日志记录所有通信
```
#### **场景 3多集群容灾**
```
需求:主集群故障时自动切换到备用集群
方案:
1. 使用 Multi-Cluster Mesh
2. 配置 ServiceEntry指向备用集群
3. 配置 DestinationRule故障时自动切换
4. 跨集群流量加密
```
---
### 9. 阿里 P7 加分项
**架构设计能力**
- 设计过大规模服务网格架构500+ 服务)
- 有多集群/多云服务网格实施经验
- 实现过自定义 Control Plane如基于 Istio API
**深度理解**
- 理解 Envoy 内部机制过滤器链、连接池、HTTP/2
- 熟悉 xDS 协议CDS, EDS, LDS, RDS
- 有性能调优经验(减少延迟、优化资源占用)
**实际项目**
- 主导过从传统架构迁移到服务网格
- 解决过生产环境的疑难问题(如网络分区、证书轮换故障)
- 开发过自定义 WASM 插件扩展 Envoy 功能
**开源贡献**
- 向 Istio/Envoy 社区提交过 PR
- 解决过社区 Issue
- 编写过相关技术博客或演讲
**监控和可观测性**
- 设计过服务网格监控体系
- 使用 Prometheus/Grafana 监控 Sidecar 性能
- 实现过分布式追踪集成Jaeger/Zipkin
**安全实践**
- 实现过零信任网络架构
- 有安全审计和合规经验
- 设计过细粒度的 RBAC 策略