云计算基础
目录
云计算概述
什么是云计算
云计算是一种按需提供计算资源(服务器、存储、数据库、网络、软件等)的模型,具有以下特征:
传统 IT 架构 云计算架构
┌────────────────┐ ┌────────────────┐
│ 物理服务器 │ │ 按需自助 │
│ ├─ 采购周期长 │ │ ├─ 秒级部署 │
│ ├─ 初期投入大 │ │ ├─ 按量付费 │
│ ├─ 资源固定 │ ────────▶ │ ├─ 弹性伸缩 │
│ ├─ 维护成本高 │ │ ├─ 高可用性 │
│ └─ 利用率低 │ │ └─ 全球部署 │
└────────────────┘ └────────────────┘NIST 云计算五大特征
┌─────────────────────────────────────────────────────┐
│ NIST 云计算定义(5-3-4 模型) │
├─────────────────────────────────────────────────────┤
│ │
│ 🔹 五大基本特征(5 Essential Characteristics) │
│ ├─ 1. 按需自助服务 (On-demand self-service) │
│ ├─ 2. 广泛网络访问 (Broad network access) │
│ ├─ 3. 资源池化 (Resource pooling) │
│ ├─ 4. 快速弹性 (Rapid elasticity) │
│ └─ 5. 可计量服务 (Measured service) │
│ │
│ 🔹 三种服务模型(3 Service Models) │
│ ├─ IaaS (Infrastructure as a Service) │
│ ├─ PaaS (Platform as a Service) │
│ └─ SaaS (Software as a Service) │
│ │
│ 🔹 四种部署模型(4 Deployment Models) │
│ ├─ 公有云 (Public Cloud) │
│ ├─ 私有云 (Private Cloud) │
│ ├─ 混合云 (Hybrid Cloud) │
│ └─ 社区云 (Community Cloud) │
└─────────────────────────────────────────────────────┘云服务模型
IaaS vs PaaS vs SaaS
┌──────────────────────────────────────────────────────────────┐
│ 云服务模型责任划分 │
├──────────────┬──────────────┬──────────────┬────────────────┤
│ 组件层次 │ 传统 IT │ IaaS │ PaaS │ SaaS │
├──────────────┼──────────────┼──────────────┼────────┼───────┤
│ Applications │ 👤 客户 │ 👤 客户 │ 👤 客户│ ☁️云商│
│ Data │ 👤 客户 │ 👤 客户 │ 👤 客户│ ☁️云商│
│ Runtime │ 👤 客户 │ 👤 客户 │ ☁️云商 │ ☁️云商│
│ Middleware │ 👤 客户 │ 👤 客户 │ ☁️云商 │ ☁️云商│
│ OS │ 👤 客户 │ 👤 客户 │ ☁️云商 │ ☁️云商│
│ Virtualization│ 👤 客户 │ ☁️云商 │ ☁️云商 │ ☁️云商│
│ Servers │ 👤 客户 │ ☁️云商 │ ☁️云商 │ ☁️云商│
│ Storage │ 👤 客户 │ ☁️云商 │ ☁️云商 │ ☁️云商│
│ Networking │ 👤 客户 │ ☁️云商 │ ☁️云商 │ ☁️云商│
└──────────────┴──────────────┴──────────────┴────────┴───────┘
👤 = 客户负责 ☁️ = 云服务商负责1. IaaS (基础设施即服务)
定义:提供虚拟化的计算资源(虚拟机、网络、存储)
典型产品:
- AWS EC2、EBS、VPC
- Azure Virtual Machines
- Google Compute Engine
- 阿里云 ECS
使用场景:
yaml
适用场景:
- 需要完全控制操作系统
- 自定义网络配置
- 运行传统应用迁移(Lift and Shift)
- 开发测试环境快速搭建
示例代码 - AWS EC2 实例创建:python
# boto3 - AWS Python SDK
import boto3
ec2 = boto3.resource('ec2', region_name='us-east-1')
# 创建 EC2 实例
instances = ec2.create_instances(
ImageId='ami-0c55b159cbfafe1f0', # Ubuntu 20.04
InstanceType='t3.medium',
MinCount=1,
MaxCount=1,
KeyName='my-key-pair',
SecurityGroupIds=['sg-0123456789abcdef0'],
SubnetId='subnet-12345678',
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [
{'Key': 'Name', 'Value': 'web-server'},
{'Key': 'Environment', 'Value': 'production'}
]
}],
BlockDeviceMappings=[{
'DeviceName': '/dev/sda1',
'Ebs': {
'VolumeSize': 100,
'VolumeType': 'gp3',
'Iops': 3000,
'DeleteOnTermination': True
}
}]
)
print(f"Created instance: {instances[0].id}")2. PaaS (平台即服务)
定义:提供应用运行平台,无需管理底层基础设施
典型产品:
- AWS Elastic Beanstalk、Lambda
- Azure App Service
- Google App Engine、Cloud Run
- Heroku
使用场景:
yaml
适用场景:
- 快速部署 Web 应用
- 无需关心服务器运维
- 专注业务逻辑开发
- Serverless 架构
示例代码 - Google Cloud Run 部署:yaml
# app.yaml - 应用配置
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: hello-service
spec:
template:
spec:
containers:
- image: gcr.io/myproject/hello:latest
ports:
- containerPort: 8080
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
resources:
limits:
memory: "512Mi"
cpu: "1000m"bash
# 部署到 Cloud Run
gcloud run deploy hello-service \
--image gcr.io/myproject/hello:latest \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars="ENV=production"3. SaaS (软件即服务)
定义:完全托管的应用软件,通过浏览器访问
典型产品:
- Google Workspace (Gmail、Docs)
- Microsoft 365
- Salesforce
- Slack、Zoom
使用场景:
yaml
适用场景:
- 企业协作工具
- CRM/ERP 系统
- 邮件服务
- 无需本地安装和维护
API 集成示例 - Salesforce:python
# simple_salesforce - Salesforce Python SDK
from simple_salesforce import Salesforce
sf = Salesforce(
username='[email protected]',
password='password',
security_token='token',
domain='test' # 使用 sandbox
)
# 创建销售机会
opportunity = sf.Opportunity.create({
'Name': 'New Deal',
'StageName': 'Prospecting',
'CloseDate': '2026-03-31',
'Amount': 50000
})
print(f"Created Opportunity: {opportunity['id']}")
# 查询数据
results = sf.query(
"SELECT Id, Name, Amount FROM Opportunity "
"WHERE StageName = 'Closed Won' AND Amount > 10000"
)
for record in results['records']:
print(f"{record['Name']}: ${record['Amount']}")云部署模型
┌─────────────────────────────────────────────────────────┐
│ 云部署模型对比 │
├─────────────┬──────────┬──────────┬──────────┬─────────┤
│ 特性 │ 公有云 │ 私有云 │ 混合云 │ 社区云 │
├─────────────┼──────────┼──────────┼──────────┼─────────┤
│ 所有权 │ 云厂商 │ 企业 │ 共享 │ 共享 │
│ 部署位置 │ 云端 │ 本地/云 │ 混合 │ 共享DC │
│ 初期成本 │ 低 │ 高 │ 中等 │ 中等 │
│ 扩展性 │ 极高 │ 受限 │ 高 │ 中等 │
│ 安全控制 │ 标准 │ 完全 │ 可定制 │ 共享 │
│ 合规性 │ 一般 │ 最佳 │ 良好 │ 良好 │
│ 典型用户 │ 创业公司│ 金融 │ 大企业 │ 政府 │
└─────────────┴──────────┴──────────┴──────────┴─────────┘混合云架构示例
混合云架构
┌─────────────────────────────────────────────┐
│ 公有云 (Public Cloud) │
│ ┌──────────────┐ ┌─────────────────┐ │
│ │ Web 前端 │ │ CDN 加速 │ │
│ │ (弹性扩展) │ │ (全球分发) │ │
│ └──────┬───────┘ └─────────────────┘ │
│ │ HTTPS │
└─────────┼─────────────────────────────────┘
│ VPN/专线
┌─────────┼─────────────────────────────────┐
│ ▼ 私有云 (Private Cloud) │
│ ┌──────────────┐ ┌─────────────────┐ │
│ │ 核心业务 │◀────▶│ 敏感数据 │ │
│ │ (稳定运行) │ │ (本地存储) │ │
│ └──────────────┘ └─────────────────┘ │
│ ▲ │
│ │ 数据同步 │
│ ┌──────┴───────┐ │
│ │ 混合云管理 │ │
│ │ (统一控制) │ │
│ └──────────────┘ │
└─────────────────────────────────────────────┘云原生架构
云原生 12 要素 (12-Factor App)
┌────────────────────────────────────────────────────────┐
│ 云原生应用 12 要素原则 │
├────────────────────────────────────────────────────────┤
│ 1. 基准代码 (Codebase) │
│ 一份代码,多处部署(Git 单一仓库) │
│ │
│ 2. 依赖 (Dependencies) │
│ 显式声明依赖(requirements.txt, go.mod) │
│ │
│ 3. 配置 (Config) │
│ 环境变量存储配置(不硬编码) │
│ │
│ 4. 后端服务 (Backing Services) │
│ 服务作为附加资源(数据库、缓存、消息队列) │
│ │
│ 5. 构建、发布、运行 (Build, Release, Run) │
│ 严格分离构建和运行阶段 │
│ │
│ 6. 进程 (Processes) │
│ 应用作为无状态进程运行 │
│ │
│ 7. 端口绑定 (Port Binding) │
│ 通过端口绑定导出服务 │
│ │
│ 8. 并发 (Concurrency) │
│ 通过进程模型进行扩展 │
│ │
│ 9. 易处理 (Disposability) │
│ 快速启动和优雅终止 │
│ │
│ 10. 开发环境与生产环境等价 (Dev/Prod Parity) │
│ 保持开发、预发、生产环境尽可能一致 │
│ │
│ 11. 日志 (Logs) │
│ 日志作为事件流输出到 stdout │
│ │
│ 12. 管理进程 (Admin Processes) │
│ 后台任务作为一次性进程运行 │
└────────────────────────────────────────────────────────┘云原生应用示例
python
# app.py - 符合 12-Factor 的 Flask 应用
import os
import logging
from flask import Flask, jsonify
from redis import Redis
import psycopg2
# 配置从环境变量读取(Factor 3)
app = Flask(__name__)
app.config['DEBUG'] = os.getenv('DEBUG', 'False') == 'True'
# 日志输出到 stdout(Factor 11)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)
# 后端服务作为附加资源(Factor 4)
redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379/0')
db_url = os.getenv('DATABASE_URL')
redis_client = Redis.from_url(redis_url)
def get_db_connection():
return psycopg2.connect(db_url)
# 端口绑定(Factor 7)
@app.route('/health')
def health():
"""健康检查端点"""
try:
redis_client.ping()
return jsonify({'status': 'healthy', 'service': 'api'}), 200
except Exception as e:
logger.error(f"Health check failed: {e}")
return jsonify({'status': 'unhealthy'}), 500
@app.route('/api/counter')
def counter():
"""无状态计数器(Factor 6)"""
count = redis_client.incr('api_calls')
logger.info(f"API called {count} times")
return jsonify({'count': count})
# 优雅关闭(Factor 9)
import signal
import sys
def signal_handler(sig, frame):
logger.info('Shutting down gracefully...')
redis_client.close()
sys.exit(0)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
if __name__ == '__main__':
port = int(os.getenv('PORT', 8080))
app.run(host='0.0.0.0', port=port)dockerfile
# Dockerfile - 构建阶段分离(Factor 5)
FROM python:3.11-slim as builder
WORKDIR /app
# 依赖显式声明(Factor 2)
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
# 运行阶段
FROM python:3.11-slim
WORKDIR /app
# 从构建阶段复制依赖
COPY --from=builder /root/.local /root/.local
COPY app.py .
# 确保脚本在 PATH 中
ENV PATH=/root/.local/bin:$PATH
# 端口声明(Factor 7)
EXPOSE 8080
# 非 root 用户运行
RUN useradd -m appuser
USER appuser
CMD ["python", "app.py"]yaml
# docker-compose.yml - 开发环境配置(Factor 10)
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- DEBUG=True
- REDIS_URL=redis://redis:6379/0
- DATABASE_URL=postgresql://user:pass@db:5432/myapp
depends_on:
- redis
- db
restart: unless-stopped
redis:
image: redis:7-alpine
ports:
- "6379:6379"
db:
image: postgres:15-alpine
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=pass
- POSTGRES_DB=myapp
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:主流云服务商
全球三大公有云对比
┌────────────────────────────────────────────────────────────┐
│ AWS vs Azure vs GCP 对比 │
├──────────┬─────────────┬──────────────┬───────────────────┤
│ 服务商 │ AWS │ Azure │ GCP │
├──────────┼─────────────┼──────────────┼───────────────────┤
│ 市场份额 │ 32% │ 23% │ 10% │
│ 成立时间 │ 2006 │ 2010 │ 2008 │
│ 全球区域 │ 31 │ 60+ │ 37 │
│ │ │ │ │
│ 计算服务 │ EC2 │ VM │ Compute Engine │
│ 容器服务 │ ECS/EKS │ AKS │ GKE │
│ 函数服务 │ Lambda │ Functions │ Cloud Functions │
│ 对象存储 │ S3 │ Blob Storage │ Cloud Storage │
│ 关系数据库│ RDS │ SQL Database │ Cloud SQL │
│ NoSQL │ DynamoDB │ Cosmos DB │ Firestore │
│ 网络 │ VPC │ Virtual Net │ VPC │
│ CDN │ CloudFront │ Front Door │ Cloud CDN │
│ AI/ML │ SageMaker │ ML Studio │ Vertex AI │
│ │ │ │ │
│ 优势 │ 生态最成熟 │ 企业集成好 │ 大数据/ML强 │
│ 劣势 │ 价格偏高 │ 文档复杂 │ 服务相对少 │
└──────────┴─────────────┴──────────────┴───────────────────┘国内云服务商对比
┌──────────────────────────────────────────────────────┐
│ 阿里云 vs 腾讯云 vs 华为云 │
├──────────┬──────────┬──────────┬───────────────────┤
│ 服务商 │ 阿里云 │ 腾讯云 │ 华为云 │
├──────────┼──────────┼──────────┼───────────────────┤
│ 市场地位 │ 第一 │ 第二 │ 第三 │
│ 优势领域 │ 电商 │ 社交/游戏│ 政企/5G │
│ 计算 │ ECS │ CVM │ ECS │
│ 容器 │ ACK │ TKE │ CCE │
│ 数据库 │ RDS/PolarDB│ CynosDB│ GaussDB │
│ AI │ PAI │ TI │ ModelArts │
└──────────┴──────────┴──────────┴───────────────────┘云迁移策略
6R 迁移策略
┌────────────────────────────────────────────────────────┐
│ 6R 迁移策略矩阵 │
├────────────┬───────────────┬───────────┬──────────────┤
│ 策略 │ 复杂度 │ 成本 │ 优化程度 │
├────────────┼───────────────┼───────────┼──────────────┤
│ Rehost │ ⭐ │ $ │ 无 │
│ (直接迁移) │ Lift & Shift │ 最低 │ 0% │
│ │ │ │ │
│ Replatform │ ⭐⭐ │ $$ │ 小幅优化 │
│ (平台优化) │ 小幅调整 │ 较低 │ 20-30% │
│ │ │ │ │
│ Repurchase │ ⭐⭐ │ $$ │ 切换到 SaaS │
│ (购买替代) │ 更换软件 │ 中等 │ 50%+ │
│ │ │ │ │
│ Refactor │ ⭐⭐⭐⭐ │ $$$$ │ 云原生改造 │
│ (重构) │ 重写代码 │ 最高 │ 80%+ │
│ │ │ │ │
│ Retire │ - │ 节省 │ 下线 │
│ (停用) │ 识别无用资源 │ │ │
│ │ │ │ │
│ Retain │ - │ 维持 │ 暂不迁移 │
│ (保留) │ 暂时保留 │ │ │
└────────────┴───────────────┴───────────┴──────────────┘迁移流程示例
云迁移六步法
┌─────────────────────────────────┐
│ 1. 评估 (Assess) │
│ ├─ 应用清单 │
│ ├─ 依赖关系 │
│ └─ 迁移成本 │
└──────────┬──────────────────────┘
│
┌──────────▼──────────────────────┐
│ 2. 准备 (Prepare) │
│ ├─ 选择迁移策略 │
│ ├─ 建立云账户 │
│ └─ 设置网络连接 │
└──────────┬──────────────────────┘
│
┌──────────▼──────────────────────┐
│ 3. 规划 (Plan) │
│ ├─ 迁移顺序 │
│ ├─ 测试计划 │
│ └─ 回滚方案 │
└──────────┬──────────────────────┘
│
┌──────────▼──────────────────────┐
│ 4. 迁移 (Migrate) │
│ ├─ 数据同步 │
│ ├─ 应用部署 │
│ └─ 验证测试 │
└──────────┬──────────────────────┘
│
┌──────────▼──────────────────────┐
│ 5. 优化 (Optimize) │
│ ├─ 性能调优 │
│ ├─ 成本优化 │
│ └─ 安全加固 │
└──────────┬──────────────────────┘
│
┌──────────▼──────────────────────┐
│ 6. 运营 (Operate) │
│ ├─ 监控告警 │
│ ├─ 持续改进 │
│ └─ FinOps 管理 │
└─────────────────────────────────┘实战案例
案例 1: 初创公司快速上云
场景:小型电商平台,日访问量 1 万
架构选择:
┌─────────────────────────────────────────┐
│ 初创公司云架构 │
├─────────────────────────────────────────┤
│ │
│ 用户 ─▶ CloudFlare CDN │
│ │ │
│ ▼ │
│ AWS ALB │
│ │ │
│ ┌────┴────┐ │
│ │ │ │
│ ECS Fargate (2个实例) │
│ │ │ │
│ └────┬────┘ │
│ │ │
│ ┌────┴────────┬────────┐ │
│ │ │ │ │
│ RDS (主从) ElastiCache S3 │
│ (t3.medium) (t3.micro) │
│ │
│ 月成本约: $500-800 │
└─────────────────────────────────────────┘Terraform 配置:
hcl
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
# VPC 配置
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = {
Name = "ecommerce-vpc"
}
}
# ECS Fargate 集群
resource "aws_ecs_cluster" "main" {
name = "ecommerce-cluster"
setting {
name = "containerInsights"
value = "enabled"
}
}
resource "aws_ecs_task_definition" "app" {
family = "ecommerce-app"
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = 512
memory = 1024
container_definitions = jsonencode([{
name = "app"
image = "myapp:latest"
portMappings = [{
containerPort = 8080
protocol = "tcp"
}]
environment = [
{ name = "DB_HOST", value = aws_db_instance.main.endpoint },
{ name = "REDIS_HOST", value = aws_elasticache_cluster.main.cache_nodes[0].address }
]
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = "/ecs/ecommerce"
"awslogs-region" = "us-east-1"
"awslogs-stream-prefix" = "app"
}
}
}])
}
# RDS MySQL
resource "aws_db_instance" "main" {
identifier = "ecommerce-db"
engine = "mysql"
engine_version = "8.0"
instance_class = "db.t3.medium"
allocated_storage = 100
storage_type = "gp3"
db_name = "ecommerce"
username = "admin"
password = var.db_password
skip_final_snapshot = false
multi_az = true
backup_retention_period = 7
tags = {
Name = "ecommerce-db"
}
}
# ElastiCache Redis
resource "aws_elasticache_cluster" "main" {
cluster_id = "ecommerce-cache"
engine = "redis"
node_type = "cache.t3.micro"
num_cache_nodes = 1
parameter_group_name = "default.redis7"
port = 6379
}
# S3 存储桶
resource "aws_s3_bucket" "assets" {
bucket = "ecommerce-assets-${random_id.bucket_suffix.hex}"
tags = {
Name = "ecommerce-assets"
}
}
resource "aws_s3_bucket_public_access_block" "assets" {
bucket = aws_s3_bucket.assets.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
resource "random_id" "bucket_suffix" {
byte_length = 4
}案例 2: 传统企业混合云改造
场景:某银行核心系统上云
架构选择:
┌──────────────────────────────────────────────────┐
│ 银行混合云架构 │
├──────────────────────────────────────────────────┤
│ │
│ 公有云(阿里云) │
│ ┌────────────────────────────────────┐ │
│ │ 互联网应用 │ │
│ │ ├─ Web 门户 (ECS 自动扩展) │ │
│ │ ├─ 移动 API (API Gateway) │ │
│ │ └─ 静态资源 (OSS + CDN) │ │
│ └────────────┬───────────────────────┘ │
│ │ 专线 (VPN/Express Connect) │
│ ─────────────┼───────────────────────────── │
│ │ │
│ 私有云(本地数据中心) │
│ ┌────────────▼───────────────────────┐ │
│ │ 核心业务系统 │ │
│ │ ├─ 账务系统 (Oracle RAC) │ │
│ │ ├─ 信贷系统 (DB2) │ │
│ │ └─ 风控系统 (私有云 K8s) │ │
│ └────────────────────────────────────┘ │
│ │
│ 数据同步: DTS (Data Transmission Service) │
│ 安全: 堡垒机 + VPN + 加密传输 │
└──────────────────────────────────────────────────┘成本优化建议
FinOps 最佳实践
┌────────────────────────────────────────────────────┐
│ 云成本优化 8 大策略 │
├────────────────────────────────────────────────────┤
│ │
│ 1. 🏷️ 资源标签管理 │
│ 按项目/部门/环境标记所有资源 │
│ │
│ 2. 💰 预留实例/Savings Plans │
│ 1-3年预留可节省 30-70% │
│ │
│ 3. 📊 Right Sizing │
│ 根据实际使用调整实例规格 │
│ │
│ 4. 🔄 Spot 实例 │
│ 非关键工作负载使用竞价实例(节省 90%) │
│ │
│ 5. ⏰ 自动化启停 │
│ 开发环境下班自动关闭 │
│ │
│ 6. 🗄️ 存储分层 │
│ 冷数据迁移到低成本存储(S3 Glacier) │
│ │
│ 7. 🌐 CDN + 对象存储 │
│ 减少带宽成本 │
│ │
│ 8. 📈 成本监控告警 │
│ 设置预算告警,定期 Review │
└────────────────────────────────────────────────────┘成本监控脚本
python
# cost_monitor.py - AWS 成本监控
import boto3
from datetime import datetime, timedelta
import json
ce = boto3.client('ce', region_name='us-east-1')
def get_monthly_cost():
"""获取本月累计成本"""
start = datetime.now().replace(day=1).strftime('%Y-%m-%d')
end = datetime.now().strftime('%Y-%m-%d')
response = ce.get_cost_and_usage(
TimePeriod={'Start': start, 'End': end},
Granularity='MONTHLY',
Metrics=['UnblendedCost'],
GroupBy=[{'Type': 'DIMENSION', 'Key': 'SERVICE'}]
)
results = response['ResultsByTime'][0]
groups = results['Groups']
print(f"📊 本月成本统计 ({start} - {end})")
print("=" * 60)
total = 0
costs = []
for group in groups:
service = group['Keys'][0]
amount = float(group['Metrics']['UnblendedCost']['Amount'])
if amount > 1: # 只显示超过 $1 的服务
costs.append((service, amount))
total += amount
# 按成本排序
costs.sort(key=lambda x: x[1], reverse=True)
for service, amount in costs[:10]: # 显示 Top 10
percentage = (amount / total) * 100
print(f"{service:30s} ${amount:10.2f} ({percentage:5.1f}%)")
print("=" * 60)
print(f"{'总计':30s} ${total:10.2f}")
return total
def check_unused_resources():
"""检查未使用的资源"""
ec2 = boto3.client('ec2')
# 检查未附加的 EBS 卷
volumes = ec2.describe_volumes(
Filters=[{'Name': 'status', 'Values': ['available']}]
)
unused_volumes = volumes['Volumes']
if unused_volumes:
print("\n⚠️ 未附加的 EBS 卷:")
total_size = 0
for vol in unused_volumes:
size = vol['Size']
total_size += size
print(f" - {vol['VolumeId']}: {size} GB")
print(f" 总计: {total_size} GB (约 ${total_size * 0.1:.2f}/月)")
# 检查未使用的 Elastic IP
addresses = ec2.describe_addresses()
unattached_eips = [
addr for addr in addresses['Addresses']
if 'InstanceId' not in addr
]
if unattached_eips:
print("\n⚠️ 未关联的 Elastic IP:")
for addr in unattached_eips:
print(f" - {addr['PublicIp']} (约 $3.6/月)")
def forecast_cost():
"""预测未来成本"""
start = datetime.now().strftime('%Y-%m-%d')
end = (datetime.now() + timedelta(days=30)).strftime('%Y-%m-%d')
response = ce.get_cost_forecast(
TimePeriod={'Start': start, 'End': end},
Metric='UNBLENDED_COST',
Granularity='MONTHLY'
)
forecast = float(response['Total']['Amount'])
print(f"\n📈 下月预测成本: ${forecast:.2f}")
if __name__ == '__main__':
current_cost = get_monthly_cost()
check_unused_resources()
forecast_cost()总结
云计算选型决策树
需要上云?
│
┌───────────┴───────────┐
│ │
是 否
│ (本地部署)
▼
控制需求 vs 便利性
│
┌────┴────┐
│ │
高控制 快速上线
│ │
▼ ▼
IaaS PaaS/SaaS
(EC2/ECS) (Fargate/Lambda)
│
▼
是否需要云原生?
│
┌─┴─┐
│ │
是 否
│ │
│ └─▶ Lift & Shift (Rehost)
│
└─▶ 容器化 (Refactor)
│
▼
Kubernetes
(EKS/GKE/AKS)关键要点
服务模型选择
- IaaS:最大控制权,适合传统应用迁移
- PaaS:快速开发,无需管理基础设施
- SaaS:开箱即用,专注业务
云原生最佳实践
- 遵循 12-Factor 原则
- 无状态设计
- 容器化部署
- 基础设施即代码
成本优化
- 合理选择实例类型
- 使用预留实例和 Spot
- 定期清理未使用资源
- 监控和预算告警
安全第一
- 最小权限原则
- 数据加密(传输和静态)
- 网络隔离
- 定期安全审计
下一步学习
- 02_serverless.md - Serverless 架构深入
- 03_cloud_patterns.md - 云设计模式
- 04_multi_cloud.md - 多云策略
- 05_cost_optimization.md - 深度成本优化
💬 讨论
使用 GitHub 账号登录后即可参与讨论