跳转至

第01章 云计算基础

云计算基础图

📚 章节概述

本章将深入讲解云计算的核心概念、服务模型、主流云平台架构以及云计算在企业中的应用。通过本章学习,你将建立对云计算的全面理解,为后续学习Docker、Kubernetes和DevOps实践打下坚实基础。

🎯 学习目标

完成本章后,你将能够:

  1. 理解云计算的定义、特点和核心价值
  2. 掌握IaaS、PaaS、SaaS三种服务模型的区别和应用场景
  3. 了解公有云、私有云、混合云、多云四种部署模型
  4. 熟悉主流云平台(AWS、Azure、GCP、阿里云、腾讯云)的核心服务
  5. 理解云计算的计费模式和成本优化策略
  6. 掌握云计算安全的基本概念和最佳实践

1.1 云计算概述

1.1.1 什么是云计算

云计算是一种通过互联网提供计算资源(服务器、存储、数据库、网络、软件等)的服务模式。用户无需购买和维护物理设备,可以根据需求弹性地获取和释放资源。

云计算的五大特征

  1. 按需自助服务(On-demand Self-service)
  2. 用户可以随时、随地获取计算资源
  3. 无需人工交互,通过Web界面或API自助服务
  4. 示例:在AWS控制台一键启动EC2实例

  5. 广泛的网络访问(Broad Network Access)

  6. 通过标准网络机制访问资源
  7. 支持多种客户端平台(PC、手机、平板等)
  8. 示例:通过手机管理阿里云ECS实例

  9. 资源池化(Resource Pooling)

  10. 多租户共享物理资源池
  11. 根据需求动态分配和释放
  12. 用户无需了解底层物理位置
  13. 示例:多个用户共享同一个物理服务器

  14. 快速弹性(Rapid Elasticity)

  15. 资源可以快速、弹性地扩展和收缩
  16. 对用户而言,资源似乎是无限的
  17. 示例:双11期间自动扩容应对流量高峰

  18. 可计量的服务(Measured Service)

  19. 资源使用情况可以被监控、测量和报告
  20. 按使用量计费,透明可控
  21. 示例:按小时计费的云服务器

1.1.2 云计算的核心价值

对企业的价值

  1. 降低成本
  2. 减少硬件采购和维护成本
  3. 按需付费,避免资源浪费
  4. 降低IT运维人力成本

  5. 提高灵活性

  6. 快速响应业务需求变化
  7. 支持全球业务扩展
  8. 加速产品上市时间

  9. 增强可靠性

  10. 多可用区部署,提高容灾能力
  11. 专业的安全团队保障
  12. 自动化运维减少人为错误

  13. 推动创新

  14. 快速试验新想法
  15. 使用最新的AI、大数据等技术
  16. 专注于核心业务创新

对开发者的价值

  1. 提升开发效率
  2. 快速搭建开发测试环境
  3. 丰富的托管服务减少开发工作量
  4. 完善的开发工具链

  5. 降低技术门槛

  6. 无需深入了解底层硬件
  7. 使用成熟的云服务
  8. 快速构建复杂应用

  9. 全球部署能力

  10. 一键部署到全球各地
  11. 边缘计算支持
  12. CDN加速

1.1.3 云计算的发展历程

Text Only
时间线:
1960s: 分时共享系统
1990s: 网络计算和网格计算
1999: Salesforce推出SaaS模式
2002: AWS推出首个云服务
2006: AWS EC2正式上线
2010: GCP和Azure相继推出
2010s: 云计算成为主流
2020s: 云原生、Serverless兴起

1.2 云计算服务模型

1.2.1 IaaS(基础设施即服务)

定义:提供虚拟化的计算资源(服务器、存储、网络),用户需要自己管理操作系统和应用程序。

核心特点

  • 提供虚拟化的硬件资源
  • 用户控制操作系统和中间件
  • 灵活性最高,管理复杂度也最高
  • 按使用量计费

典型服务

  • 计算:AWS EC2、阿里云ECS、腾讯云CVM
  • 存储:AWS S3、阿里云OSS、腾讯云COS
  • 网络:AWS VPC、阿里云VPC、腾讯云VPC
  • 数据库:AWS RDS、阿里云RDS、腾讯云MySQL

适用场景

  • 需要完全控制基础设施的场景
  • 传统应用的云迁移
  • 需要自定义操作系统配置
  • 对性能和安全有特殊要求

示例代码:使用AWS SDK创建EC2实例

Python
import boto3
from datetime import datetime, timedelta

def create_ec2_instance():
    """
    创建AWS EC2实例
    """
    # 创建EC2客户端
    ec2 = boto3.client('ec2', region_name='us-east-1')

    # 实例配置
    instance_params = {
        'ImageId': 'ami-0c55b159cbfafe1f0',  # Amazon Linux 2 AMI
        'InstanceType': 't2.micro',
        'MinCount': 1,
        'MaxCount': 1,
        'KeyName': 'my-key-pair',
        'SecurityGroupIds': ['sg-12345678'],
        'SubnetId': 'subnet-12345678',
        'UserData': '''#!/bin/bash
            # 安装Docker
            yum install -y docker
            service docker start
            usermod -aG docker ec2-user
        ''',
        'TagSpecifications': [
            {
                'ResourceType': 'instance',
                'Tags': [
                    {'Key': 'Name', 'Value': 'my-web-server'},
                    {'Key': 'Environment', 'Value': 'production'}
                ]
            }
        ]
    }

    # 创建实例
    response = ec2.run_instances(**instance_params)

    instance_id = response['Instances'][0]['InstanceId']
    print(f"EC2实例创建成功: {instance_id}")

    # 等待实例运行
    waiter = ec2.get_waiter('instance_running')
    waiter.wait(InstanceIds=[instance_id])

    # 获取实例信息
    instance = ec2.describe_instances(InstanceIds=[instance_id])
    public_ip = instance['Reservations'][0]['Instances'][0]['PublicIpAddress']

    print(f"实例公网IP: {public_ip}")
    return instance_id

if __name__ == '__main__':
    create_ec2_instance()

1.2.2 PaaS(平台即服务)

定义:提供应用程序开发和运行平台,用户只需关注应用代码,无需管理底层基础设施。

核心特点

  • 提供开发、运行环境
  • 自动扩展和负载均衡
  • 内置数据库、缓存等服务
  • 管理复杂度中等

典型服务

  • 应用平台:AWS Elastic Beanstalk、阿里云应用引擎、腾讯云云开发
  • 数据库服务:AWS DynamoDB、阿里云TableStore
  • 消息队列:AWS SQS、阿里云消息队列
  • 缓存服务:AWS ElastiCache、阿里云Redis

适用场景

  • Web应用和API服务
  • 快速开发和部署
  • 团队协作开发
  • 需要自动扩展的应用

示例代码:使用AWS Elastic Beanstalk部署应用

Python
import boto3

def deploy_application():
    """
    使用Elastic Beanstalk部署应用
    """
    eb = boto3.client('elasticbeanstalk', region_name='us-east-1')

    # 应用配置
    app_name = 'my-web-app'
    env_name = 'my-web-app-prod'

    # 创建应用
    try:
        response = eb.create_application(
            ApplicationName=app_name,
            Description='My Web Application'
        )
        print(f"应用创建成功: {app_name}")
    except eb.exceptions.ApplicationAlreadyExistsException:
        print(f"应用已存在: {app_name}")

    # 创建环境
    response = eb.create_environment(
        ApplicationName=app_name,
        EnvironmentName=env_name,
        SolutionStackName='64bit Amazon Linux 2 v5.8.0 running Python 3.11',
        OptionSettings=[
            {
                'Namespace': 'aws:elasticbeanstalk:container:python',
                'OptionName': 'WSGIPath',
                'Value': 'application.py'
            },
            {
                'Namespace': 'aws:autoscaling:asg',
                'OptionName': 'MinSize',
                'Value': '2'
            },
            {
                'Namespace': 'aws:autoscaling:asg',
                'OptionName': 'MaxSize',
                'Value': '6'
            }
        ]
    )

    print(f"环境创建成功: {env_name}")
    return response

if __name__ == '__main__':
    deploy_application()

1.2.3 SaaS(软件即服务)

定义:提供完整的软件应用,用户通过浏览器或客户端直接使用,无需管理任何基础设施。

核心特点

  • 开箱即用
  • 自动更新和维护
  • 多租户架构
  • 管理复杂度最低

典型服务

  • 办公软件:Office 365、Google Workspace
  • CRM:Salesforce、阿里云CRM
  • 协作工具:Slack、钉钉、企业微信
  • 数据分析:Tableau Online、阿里云Quick BI

适用场景

  • 标准化业务流程
  • 快速部署和使用
  • 无需定制化开发
  • 降低IT维护成本

1.2.4 三种服务模型对比

特性 IaaS PaaS SaaS
管理复杂度
灵活性
控制力 完全控制 部分控制 最小控制
成本 按资源计费 按使用计费 订阅制
技术门槛
部署速度 最快
适用场景 自定义应用 Web应用 标准软件

1.3 云计算部署模型

1.3.1 公有云(Public Cloud)

定义:由第三方云服务提供商运营,通过互联网向公众提供云服务。

优点

  • 无需前期硬件投资
  • 弹性扩展,按需付费
  • 专业团队维护
  • 全球基础设施

缺点

  • 数据安全顾虑
  • 合规性挑战
  • 供应商锁定风险
  • 网络依赖

典型提供商

  • AWS(Amazon Web Services)
  • Microsoft Azure
  • Google Cloud Platform(GCP)
  • 阿里云
  • 腾讯云
  • 华为云

适用场景

  • 初创企业和中小企业
  • 波动性业务
  • 全球业务
  • 快速原型开发

1.3.2 私有云(Private Cloud)

定义:由企业自己拥有和运营,专门为单一组织提供云服务。

优点

  • 完全控制和安全
  • 满足合规要求
  • 性能可预测
  • 数据隐私保护

缺点

  • 前期投资大
  • 维护成本高
  • 扩展受限
  • 需要专业团队

技术栈

  • OpenStack
  • VMware vSphere
  • Apache CloudStack
  • Kubernetes

适用场景

  • 金融、医疗等高度监管行业
  • 对数据安全有严格要求
  • 有稳定的大规模需求
  • 已有数据中心资源

示例架构:基于Kubernetes的私有云

YAML
# 私有云集群配置示例
apiVersion: v1  # apiVersion指定K8s API版本
kind: ConfigMap  # kind指定资源类型
metadata:
  name: cloud-config
  namespace: kube-system
data:
  config.yaml: |
    apiVersion: cloudprovider/v1
    kind: CloudConfig
    global:
      project-id: "my-private-cloud"
      network-name: "private-network"

    nodes:
      - name: "master-01"
        role: "master"
        ip: "192.168.1.10"
      - name: "worker-01"
        role: "worker"
        ip: "192.168.1.11"
      - name: "worker-02"
        role: "worker"
        ip: "192.168.1.12"

    storage:
      - name: "ceph-storage"
        type: "ceph"
        monitors:
          - "192.168.1.20:6789"
          - "192.168.1.21:6789"
          - "192.168.1.22:6789"

1.3.3 混合云(Hybrid Cloud)

定义:结合公有云和私有云,通过专用连接或VPN实现数据和应用的互通。

优点

  • 灵活性和安全性兼顾
  • 优化成本和性能
  • 灾难恢复能力
  • 渐进式云迁移

挑战

  • 架构复杂度高
  • 数据一致性
  • 网络连接稳定性
  • 统一管理困难

典型架构模式

  1. 扩展模式
  2. 核心业务在私有云
  3. 峰值流量扩展到公有云

  4. 灾备模式

  5. 主环境在私有云
  6. 备份环境在公有云

  7. 数据处理模式

  8. 敏感数据在私有云
  9. 非敏感数据在公有云

示例:混合云网络架构

Python
import boto3

def setup_hybrid_cloud():
    """
    搭建混合云网络连接
    """
    # 创建AWS Direct Connect连接
    directconnect = boto3.client('directconnect', region_name='us-east-1')

    # 创建连接
    connection = directconnect.create_connection(
        locationName='EqDC2',
        bandwidth='1Gbps',
        connectionName='hybrid-cloud-connection'
    )

    connection_id = connection['connectionId']
    print(f"Direct Connect连接创建成功: {connection_id}")

    # 创建虚拟接口
    vif = directconnect.create_private_virtual_interface(
        connectionId=connection_id,
        newPrivateVirtualInterface={
            'virtualInterfaceName': 'hybrid-cloud-vif',
            'vlan': 100,
            'asn': 65000,
            'authKey': 'my-auth-key',
            'amazonAddress': '169.254.1.1/30',
            'customerAddress': '169.254.1.2/30',
            'virtualGatewayId': 'vgw-12345678'
        }
    )

    print(f"虚拟接口创建成功: {vif['virtualInterfaceId']}")

    # 配置路由
    ec2 = boto3.client('ec2', region_name='us-east-1')
    ec2.create_route(
        RouteTableId='rtb-12345678',
        DestinationCidrBlock='192.168.0.0/16',
        GatewayId='vgw-12345678'
    )

    print("混合云网络配置完成")
    return connection_id

if __name__ == '__main__':
    setup_hybrid_cloud()

1.3.4 多云(Multi-Cloud)

定义:同时使用多个云服务提供商的服务,避免供应商锁定。

优点

  • 避免供应商锁定
  • 优化成本
  • 提高可用性
  • 利用各云平台优势

挑战

  • 管理复杂度高
  • 数据同步困难
  • 技术栈差异
  • 成本增加

多云管理策略

  1. 统一管理平台
  2. Terraform
  3. Ansible
  4. 跨云管理工具

  5. 标准化架构

  6. 容器化应用
  7. 云原生架构
  8. 统一API接口

  9. 自动化部署

  10. CI/CD流水线
  11. 基础设施即代码
  12. 自动化测试

1.4 主流云平台介绍

1.4.1 AWS(Amazon Web Services)

概述

AWS是全球最大的云服务提供商,提供200+项服务,覆盖计算、存储、数据库、网络、AI、物联网等各个领域。

核心服务

服务类别 核心服务 用途
计算 EC2, Lambda, Fargate 虚拟机、Serverless、容器
存储 S3, EBS, EFS 对象存储、块存储、文件存储
数据库 RDS, DynamoDB, Aurora 关系型数据库、NoSQL
网络 VPC, CloudFront, Route 53 虚拟网络、CDN、DNS
AI/ML SageMaker, Rekognition 机器学习平台、图像识别
大数据 EMR, Redshift, Athena 大数据处理、数据仓库

优势

  • 服务最全面
  • 生态最成熟
  • 全球基础设施
  • 文档完善

示例:使用AWS SDK上传文件到S3

Python
import boto3
from botocore.exceptions import ClientError

def upload_file_to_s3(file_path, bucket_name, object_name=None):
    """
    上传文件到S3
    """
    # 创建S3客户端
    s3_client = boto3.client('s3', region_name='us-east-1')

    # 如果未指定对象名称,使用文件名
    if object_name is None:
        object_name = file_path.split('/')[-1]  # 负索引:从末尾倒数访问元素

    try:
        # 上传文件
        response = s3_client.upload_file(
            file_path,
            bucket_name,
            object_name,
            ExtraArgs={
                'ContentType': 'application/octet-stream',
                'Metadata': {
                    'uploaded-by': 'devops-team',
                    'environment': 'production'
                }
            }
        )

        # 设置生命周期策略
        s3_client.put_object_lifecycle_configuration(
            Bucket=bucket_name,
            LifecycleConfiguration={
                'Rules': [
                    {
                        'Id': 'DeleteOldFiles',
                        'Status': 'Enabled',
                        'Filter': {'Prefix': 'logs/'},
                        'Expiration': {'Days': 30}
                    }
                ]
            }
        )

        print(f"文件上传成功: {object_name}")
        return True

    except ClientError as e:
        print(f"上传失败: {e}")
        return False

def download_file_from_s3(bucket_name, object_name, file_path):
    """
    从S3下载文件
    """
    s3_client = boto3.client('s3', region_name='us-east-1')

    try:
        s3_client.download_file(bucket_name, object_name, file_path)
        print(f"文件下载成功: {file_path}")
        return True
    except ClientError as e:
        print(f"下载失败: {e}")
        return False

if __name__ == '__main__':
    # 上传文件
    upload_file_to_s3('data.csv', 'my-bucket', 'data/data.csv')

    # 下载文件
    download_file_from_s3('my-bucket', 'data/data.csv', 'downloaded_data.csv')

1.4.2 Microsoft Azure

概述

Azure是微软的云平台,与企业级应用和Windows生态系统深度集成。

核心服务

服务类别 核心服务 用途
计算 Azure VM, Azure Functions, AKS 虚拟机、Serverless、K8s
存储 Blob Storage, Disk Storage 对象存储、磁盘存储
数据库 SQL Database, Cosmos DB SQL数据库、NoSQL
网络 VNet, Azure Front Door 虚拟网络、CDN
AI/ML Azure ML, Cognitive Services 机器学习、认知服务
DevOps Azure DevOps, GitHub Actions CI/CD、代码管理

优势

  • 与Windows生态集成
  • 企业级服务完善
  • 混合云能力强
  • Office 365集成

示例:使用Azure SDK创建虚拟机

Python
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.resource import ResourceManagementClient

def create_azure_vm():
    """
    创建Azure虚拟机
    """
    # 认证
    credential = DefaultAzureCredential()

    # 创建客户端
    compute_client = ComputeManagementClient(
        credential,
        subscription_id='your-subscription-id'
    )
    resource_client = ResourceManagementClient(
        credential,
        subscription_id='your-subscription-id'
    )

    # 资源组配置
    RESOURCE_GROUP_NAME = 'my-resource-group'
    LOCATION = 'eastus'

    # 创建资源组
    resource_client.resource_groups.create_or_update(
        RESOURCE_GROUP_NAME,
        {'location': LOCATION}
    )

    # VM配置
    vm_parameters = {
        'location': LOCATION,
        'os_profile': {
            'computer_name': 'my-vm',
            'admin_username': 'azureuser',
            'admin_password': 'Password123!',
            'disable_password_authentication': False
        },
        'hardware_profile': {
            'vm_size': 'Standard_DS1_v2'
        },
        'storage_profile': {
            'image_reference': {
                'publisher': 'Canonical',
                'offer': '0001-com-ubuntu-server-jammy',
                'sku': '22_04-lts-gen2',
                'version': 'latest'
            },
            'os_disk': {
                'create_option': 'FromImage',
                'managed_disk': {
                    'storage_account_type': 'Standard_LRS'
                }
            }
        },
        'network_profile': {
            'network_interfaces': [{
                'id': '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/networkInterfaces/my-nic'.format(
                    'your-subscription-id',
                    RESOURCE_GROUP_NAME
                )
            }]
        }
    }

    # 创建VM
    poller = compute_client.virtual_machines.begin_create_or_update(
        RESOURCE_GROUP_NAME,
        'my-vm',
        vm_parameters
    )

    vm_result = poller.result()
    print(f"虚拟机创建成功: {vm_result.name}")

    return vm_result

if __name__ == '__main__':
    create_azure_vm()

1.4.3 Google Cloud Platform(GCP)

概述

GCP是谷歌的云平台,以数据分析、AI/ML和容器技术见长。

核心服务

服务类别 核心服务 用途
计算 Compute Engine, Cloud Functions, GKE 虚拟机、Serverless、K8s
存储 Cloud Storage, Persistent Disk 对象存储、持久磁盘
数据库 Cloud SQL, Firestore, Bigtable SQL数据库、NoSQL
网络 VPC, Cloud CDN, Cloud Load Balancing 虚拟网络、CDN、负载均衡
AI/ML Vertex AI, TensorFlow 机器学习平台
大数据 BigQuery, Dataflow, Dataproc 数据分析、流处理

优势

  • 数据分析能力强
  • Kubernetes技术领先
  • AI/ML集成好
  • 性价比高

示例:使用GCP SDK创建BigQuery数据集

Python
from google.cloud import bigquery
from google.cloud.exceptions import NotFound

def create_bigquery_dataset():
    """
    创建BigQuery数据集
    """
    # 创建客户端
    client = bigquery.Client()

    # 数据集配置
    dataset_id = "my-project.my_dataset"
    dataset = bigquery.Dataset(dataset_id)

    # 设置数据集属性
    dataset.description = "My production dataset"
    dataset.location = "US"
    dataset.default_table_expiration_ms = 30 * 24 * 60 * 60 * 1000  # 30天

    # 创建数据集
    try:
        dataset = client.create_dataset(dataset)
        print(f"数据集创建成功: {dataset.dataset_id}")
    except Exception as e:
        print(f"数据集创建失败: {e}")
        return None

    # 创建表
    table_id = f"{dataset_id}.user_events"
    schema = [
        bigquery.SchemaField("event_id", "STRING"),
        bigquery.SchemaField("user_id", "STRING"),
        bigquery.SchemaField("event_type", "STRING"),
        bigquery.SchemaField("event_time", "TIMESTAMP"),
        bigquery.SchemaField("properties", "JSON"),
    ]

    table = bigquery.Table(table_id, schema=schema)
    table.description = "User events tracking"
    table = client.create_table(table)

    print(f"表创建成功: {table.table_id}")

    return dataset

def query_bigquery():
    """
    查询BigQuery数据
    """
    client = bigquery.Client()

    query = """
        SELECT
            event_type,
            COUNT(*) as event_count,
            COUNT(DISTINCT user_id) as unique_users
        FROM
            `my-project.my_dataset.user_events`
        WHERE
            event_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
        GROUP BY
            event_type
        ORDER BY
            event_count DESC
    """

    query_job = client.query(query)
    results = query_job.result()

    for row in results:
        print(f"{row.event_type}: {row.event_count} events, {row.unique_users} users")

if __name__ == '__main__':
    create_bigquery_dataset()
    query_bigquery()

1.4.4 阿里云

概述

阿里云是中国最大的云服务提供商,在国内市场占有率第一。

核心服务

服务类别 核心服务 用途
计算 ECS, ECI, ACK 云服务器、容器实例、K8s
存储 OSS, OSS-HDFS, NAS 对象存储、HDFS、文件存储
数据库 RDS, PolarDB, OceanBase 关系型数据库、分布式数据库
网络 VPC, CDN, SLB 虚拟网络、CDN、负载均衡
AI/ML PAI, EAS 机器学习平台
大数据 MaxCompute, DataWorks 大数据计算、数据开发

优势

  • 国内基础设施完善
  • 合规性好
  • 本地化服务
  • 性价比高

示例:使用阿里云SDK创建ECS实例

Python
from alibabacloud_ecs20140526.client import Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ecs20140526 import models as ecs_models
import json

def create_aliyun_ecs():
    """
    创建阿里云ECS实例
    """
    # 配置客户端
    config = open_api_models.Config(
        access_key_id='your-access-key-id',
        access_key_secret='your-access-key-secret',
        region_id='cn-hangzhou'
    )
    config.endpoint = 'ecs.cn-hangzhou.aliyuncs.com'

    client = Client(config)

    # 实例配置
    create_instance_request = ecs_models.CreateInstanceRequest(
        region_id='cn-hangzhou',
        image_id='ubuntu_20_04_x64_20G_alibase_20230727.vhd',
        instance_type='ecs.t6-c1m1.large',
        security_group_id='sg-12345678',
        v_switch_id='vsw-12345678',
        instance_name='my-web-server',
        description='Web server for production',
        internet_max_bandwidth_out=5,
        system_disk_category='cloud_essd',
        system_disk_size=40,
        data_disks=[
            ecs_models.CreateInstanceRequestDataDisks(
                category='cloud_essd',
                size=100
            )
        ],
        tags=[
            ecs_models.CreateInstanceRequestTags(
                key='Environment',
                value='production'
            ),
            ecs_models.CreateInstanceRequestTags(
                key='Owner',
                value='devops-team'
            )
        ]
    )

    # 创建实例
    response = client.create_instance(create_instance_request)
    instance_id = response.body.instance_id

    print(f"ECS实例创建成功: {instance_id}")

    # 等待实例启动
    import time
    time.sleep(30)

    # 启动实例
    start_instance_request = ecs_models.StartInstanceRequest(
        instance_id=instance_id
    )
    client.start_instance(start_instance_request)

    print(f"ECS实例启动成功: {instance_id}")

    return instance_id

if __name__ == '__main__':
    create_aliyun_ecs()

1.4.5 腾讯云

概述

腾讯云是腾讯旗下的云服务平台,在游戏、视频、社交等领域有优势。

核心服务

服务类别 核心服务 用途
计算 CVM, Serverless, TKE 云服务器、Serverless、K8s
存储 COS, CFS 对象存储、文件存储
数据库 MySQL, TDSQL, MongoDB 关系型数据库、分布式数据库
网络 VPC, CDN, CLB 虚拟网络、CDN、负载均衡
AI/ML TI-ONE, TI-Matrix 机器学习平台
大数据 EMR, Oceanus 大数据计算、流处理

优势

  • 游戏行业经验丰富
  • 视频处理能力强
  • 社交生态集成
  • 性价比高

1.5 云计算计费与成本优化

1.5.1 云计算计费模式

按需计费(On-Demand)

  • 特点:按使用时间计费,灵活但单价高
  • 适用:测试环境、波动性业务
  • 示例:AWS EC2按小时计费

预留实例(Reserved Instance)

  • 特点:预付费用,享受折扣
  • 适用:稳定的生产环境
  • 示例:AWS RI可节省高达75%

Spot实例

  • 特点:竞价获取,价格低但可能被回收
  • 适用:批处理、容错任务
  • 示例:AWS Spot Instance可节省90%

Savings Plans

  • 特点:承诺使用量,享受折扣
  • 适用:可预测的工作负载
  • 示例:AWS Compute Savings Plans

1.5.2 成本优化策略

1. 资源优化

  • 选择合适的实例类型
  • 自动调整实例大小
  • 清理未使用的资源
  • 使用Spot实例

2. 架构优化

  • 使用Serverless架构
  • 采用微服务架构
  • 实施自动扩缩容
  • 优化数据传输

3. 购买策略

  • 使用预留实例
  • 购买Savings Plans
  • 混合使用计费模式
  • 关注区域价格差异

4. 监控和分析

  • 实施成本监控
  • 定期成本分析
  • 设置成本告警
  • 成本分摊和归因

示例:成本监控脚本

Python
import boto3
from datetime import datetime, timedelta

def analyze_cloud_costs():
    """
    分析云成本
    """
    # 创建Cost Explorer客户端
    ce = boto3.client('ce', region_name='us-east-1')

    # 查询最近30天的成本
    end_date = datetime.now().strftime('%Y-%m-%d')
    start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')

    # 按服务查询成本
    response = ce.get_cost_and_usage(
        TimePeriod={
            'Start': start_date,
            'End': end_date
        },
        Granularity='DAILY',
        Metrics=['BlendedCost', 'UnblendedCost'],
        GroupBy=[
            {
                'Type': 'DIMENSION',
                'Key': 'SERVICE'
            }
        ]
    )

    # 分析结果
    print("成本分析报告")
    print("=" * 50)
    total_cost = 0

    for result in response['ResultsByTime']:
        date = result['TimePeriod']['Start']
        print(f"\n日期: {date}")

        for group in result['Groups']:
            service = group['Keys'][0]
            cost = float(group['Metrics']['BlendedCost']['Amount'])
            total_cost += cost
            print(f"  {service}: ${cost:.2f}")

    print(f"\n总成本: ${total_cost:.2f}")

    # 按标签查询成本
    tagged_response = ce.get_cost_and_usage(
        TimePeriod={
            'Start': start_date,
            'End': end_date
        },
        Granularity='MONTHLY',
        Metrics=['BlendedCost'],
        GroupBy=[
            {
                'Type': 'TAG',
                'Key': 'Environment'
            }
        ]
    )

    print("\n按环境分摊成本:")
    print("-" * 50)
    for result in tagged_response['ResultsByTime']:
        for group in result['Groups']:
            if group['Keys'][0]:  # 忽略无标签的资源
                environment = group['Keys'][0]
                cost = float(group['Metrics']['BlendedCost']['Amount'])
                print(f"{environment}: ${cost:.2f}")

    return total_cost

def set_budget_alert():
    """
    设置成本告警
    """
    # 创建Budgets客户端
    budgets = boto3.client('budgets', region_name='us-east-1')

    # 创建月度预算
    budget = {
        'AccountId': '123456789012',
        'Budget': {
            'BudgetName': 'MonthlyCostBudget',
            'BudgetLimit': {
                'Amount': '1000.00',
                'Unit': 'USD'
            },
            'TimeUnit': 'MONTHLY',
            'BudgetType': 'COST',
            'CostFilters': {
                'Service': ['Amazon EC2', 'Amazon RDS', 'Amazon S3']
            }
        },
        'NotificationsWithSubscribers': [
            {
                'Notification': {
                    'NotificationType': 'ACTUAL',
                    'ComparisonOperator': 'GREATER_THAN',
                    'Threshold': 80.0,
                    'ThresholdType': 'PERCENTAGE'
                },
                'Subscribers': [
                    {
                        'SubscriptionType': 'EMAIL',
                        'Address': 'devops-team@example.com'
                    },
                    {
                        'SubscriptionType': 'SNS',
                        'Address': 'arn:aws:sns:us-east-1:123456789012:cost-alerts'
                    }
                ]
            }
        ]
    }

    try:
        budgets.create_budget(**budget)
        print("成本告警设置成功")
    except Exception as e:
        print(f"设置失败: {e}")

if __name__ == '__main__':
    analyze_cloud_costs()
    set_budget_alert()

1.6 云计算安全基础

1.6.1 共享责任模型

云计算安全遵循共享责任模型,明确云服务商和用户各自的责任。

AWS共享责任模型

责任方 责任范围
AWS 物理安全、网络基础设施、虚拟化层
用户 数据安全、操作系统、应用、配置

不同服务模型的责任划分

服务模型 云服务商责任 用户责任
IaaS 物理到虚拟化 操作系统到应用
PaaS 物理到操作系统 数据到应用
SaaS 物理到应用 数据和用户行为

1.6.2 核心安全概念

1. 身份和访问管理(IAM)

  • 最小权限原则
  • 多因素认证(MFA)
  • 访问密钥轮换
  • 审计日志

2. 网络安全

  • VPC隔离
  • 安全组规则
  • 网络ACL
  • VPN和Direct Connect

3. 数据安全

  • 加密(静态和传输)
  • 密钥管理
  • 数据分类
  • 备份和恢复

4. 合规性

  • 等保2.0
  • GDPR
  • ISO 27001
  • SOC 2

1.6.3 安全最佳实践

示例:IAM安全配置

Python
import boto3
import json

def setup_iam_security():
    """
    设置IAM安全配置
    """
    iam = boto3.client('iam', region_name='us-east-1')

    # 1. 创建自定义策略(最小权限)
    policy_document = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "s3:GetObject",
                    "s3:PutObject"
                ],
                "Resource": "arn:aws:s3:::my-bucket/*",
                "Condition": {
                    "IpAddress": {
                        "aws:SourceIp": ["192.0.2.0/24"]
                    }
                }
            }
        ]
    }

    try:
        policy = iam.create_policy(
            PolicyName='S3ReadOnlyForSpecificIP',
            PolicyDocument=json.dumps(policy_document),
            Description='Allow S3 access from specific IP range'
        )
        print(f"策略创建成功: {policy['Policy']['Arn']}")
    except Exception as e:
        print(f"策略创建失败: {e}")

    # 2. 创建用户并分配策略
    try:
        user = iam.create_user(
            UserName='devops-user',
            Path='/developers/'
        )
        print(f"用户创建成功: {user['User']['UserName']}")
    except Exception as e:
        print(f"用户创建失败: {e}")

    # 3. 分配策略
    iam.attach_user_policy(
        UserName='devops-user',
        PolicyArn='arn:aws:iam::123456789012:policy/S3ReadOnlyForSpecificIP'
    )

    # 4. 创建访问密钥(生产环境应使用临时凭证)
    try:
        keys = iam.create_access_key(UserName='devops-user')
        print(f"访问密钥创建成功:")
        print(f"  Access Key ID: {keys['AccessKey']['AccessKeyId']}")
        print(f"  Secret Access Key: {keys['AccessKey']['SecretAccessKey']}")
        print("请妥善保管密钥,不要泄露!")
    except Exception as e:
        print(f"访问密钥创建失败: {e}")

    # 5. 启用MFA(需要用户在控制台操作)
    print("\n安全提醒:")
    print("1. 请为用户devops-user启用MFA")
    print("2. 定期轮换访问密钥")
    print("3. 使用临时凭证而非长期密钥")
    print("4. 定期审计IAM权限")

def audit_iam_permissions():
    """
    审计IAM权限
    """
    iam = boto3.client('iam', region_name='us-east-1')

    # 获取所有用户
    users = iam.list_users()

    print("IAM权限审计报告")
    print("=" * 50)

    for user in users['Users']:
        username = user['UserName']
        print(f"\n用户: {username}")

        # 检查访问密钥
        access_keys = iam.list_access_keys(UserName=username)
        for key in access_keys['AccessKeyMetadata']:
            key_id = key['AccessKeyId']
            status = key['Status']
            create_date = key['CreateDate']

            # 检查密钥年龄
            key_age = (datetime.now() - create_date.replace(tzinfo=None)).days

            print(f"  密钥: {key_id}")
            print(f"    状态: {status}")
            print(f"    创建时间: {create_date}")
            print(f"    密钥年龄: {key_age}天")

            if key_age > 90:
                print("    ⚠️ 警告: 密钥超过90天,建议轮换")

        # 检查MFA
        try:
            mfa_devices = iam.list_mfa_devices(UserName=username)
            if not mfa_devices['MFADevices']:
                print("  ⚠️ 警告: 未启用MFA")
            else:
                print("  ✓ MFA已启用")
        except Exception as e:
            print(f"  MFA检查失败: {e}")

        # 检查附加的策略
        policies = iam.list_attached_user_policies(UserName=username)
        print(f"  附加策略数量: {len(policies['AttachedPolicies'])}")

if __name__ == '__main__':
    setup_iam_security()
    print("\n")
    audit_iam_permissions()

1.7 实战案例:构建云端Web应用

案例概述

我们将构建一个完整的云端Web应用,包括: 1. 使用EC2部署Web服务器 2. 使用S3存储静态资源 3. 使用RDS作为数据库 4. 使用CloudFront做CDN加速 5. 实施自动扩缩容

架构设计

Text Only
                    ┌─────────────┐
                    │   用户      │
                    └──────┬──────┘
                    ┌──────▼──────┐
                    │  CloudFront │
                    │    (CDN)    │
                    └──────┬──────┘
              ┌────────────┼────────────┐
              │            │            │
        ┌─────▼─────┐ ┌───▼────┐ ┌─────▼─────┐
        │   S3      │ │  ALB   │ │   RDS     │
        │ (静态资源) │ │(负载均衡)│ │ (数据库)  │
        └───────────┘ └───┬────┘ └───────────┘
                    ┌──────▼──────┐
                    │ Auto Scaling │
                    │   Group     │
                    └──────┬──────┘
              ┌────────────┼────────────┐
              │            │            │
        ┌─────▼─────┐ ┌───▼────┐ ┌─────▼─────┐
        │  EC2-1    │ │ EC2-2  │ │  EC2-3    │
        │ (Web服务器)│ │(Web服务器)│ │(Web服务器)│
        └───────────┘ └────────┘ └───────────┘

完整实现代码

Python
import boto3
import time
from datetime import datetime

class CloudWebApp:
    """云端Web应用部署类"""

    def __init__(self, region='us-east-1'):
        self.region = region
        self.ec2 = boto3.client('ec2', region_name=region)
        self.s3 = boto3.client('s3', region_name=region)
        self.rds = boto3.client('rds', region_name=region)
        self.elbv2 = boto3.client('elbv2', region_name=region)
        self.autoscaling = boto3.client('autoscaling', region_name=region)
        self.cloudfront = boto3.client('cloudfront')

        self.vpc_id = None
        self.subnet_ids = []
        self.security_group_id = None
        self.instance_ids = []
        self.load_balancer_arn = None
        self.target_group_arn = None

    def create_vpc(self):
        """创建VPC网络"""
        print("创建VPC...")

        # 创建VPC
        vpc_response = self.ec2.create_vpc(
            CidrBlock='10.0.0.0/16',
            AmazonProvidedIpv6CidrBlock=False,
            InstanceTenancy='default'
        )
        self.vpc_id = vpc_response['Vpc']['VpcId']

        # 启用DNS支持
        self.ec2.modify_vpc_attribute(
            VpcId=self.vpc_id,
            EnableDnsSupport={'Value': True}
        )
        self.ec2.modify_vpc_attribute(
            VpcId=self.vpc_id,
            EnableDnsHostnames={'Value': True}
        )

        # 创建子网
        for i in range(3):
            subnet_response = self.ec2.create_subnet(
                VpcId=self.vpc_id,
                CidrBlock=f'10.0.{i}.0/24',
                AvailabilityZone=f'{self.region}{chr(97 + i)}'
            )
            self.subnet_ids.append(subnet_response['Subnet']['SubnetId'])

        # 创建Internet网关
        igw_response = self.ec2.create_internet_gateway()
        igw_id = igw_response['InternetGateway']['InternetGatewayId']

        # 关联Internet网关
        self.ec2.attach_internet_gateway(
            InternetGatewayId=igw_id,
            VpcId=self.vpc_id
        )

        # 创建路由表
        route_table_response = self.ec2.create_route_table(VpcId=self.vpc_id)
        route_table_id = route_table_response['RouteTable']['RouteTableId']

        # 添加路由
        self.ec2.create_route(
            RouteTableId=route_table_id,
            DestinationCidrBlock='0.0.0.0/0',
            GatewayId=igw_id
        )

        # 关联子网
        for subnet_id in self.subnet_ids:
            self.ec2.associate_route_table(
                RouteTableId=route_table_id,
                SubnetId=subnet_id
            )

        print(f"VPC创建完成: {self.vpc_id}")

    def create_security_group(self):
        """创建安全组"""
        print("创建安全组...")

        sg_response = self.ec2.create_security_group(
            GroupName='web-app-sg',
            Description='Security group for web application',
            VpcId=self.vpc_id
        )
        self.security_group_id = sg_response['GroupId']

        # 添加入站规则
        self.ec2.authorize_security_group_ingress(
            GroupId=self.security_group_id,
            IpPermissions=[
                {
                    'IpProtocol': 'tcp',
                    'FromPort': 80,
                    'ToPort': 80,
                    'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
                },
                {
                    'IpProtocol': 'tcp',
                    'FromPort': 443,
                    'ToPort': 443,
                    'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
                },
                {
                    'IpProtocol': 'tcp',
                    'FromPort': 22,
                    'ToPort': 22,
                    'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
                }
            ]
        )

        print(f"安全组创建完成: {self.security_group_id}")

    def create_launch_template(self):
        """创建启动模板"""
        print("创建启动模板...")

        # 用户数据脚本
        user_data = '''#!/bin/bash
            # 更新系统
            yum update -y

            # 安装Docker
            yum install -y docker
            service docker start
            usermod -aG docker ec2-user

            # 拉取并运行Web应用
            docker run -d -p 80:80 nginx:latest

            # 安装CloudWatch Agent
            yum install -y amazon-cloudwatch-agent
            /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
                -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/etc/config.json
        '''

        # 创建启动模板
        ec2 = boto3.client('ec2', region_name=self.region)
        template_response = ec2.create_launch_template(
            LaunchTemplateName='web-app-template',
            LaunchTemplateData={
                'ImageId': 'ami-0c55b159cbfafe1f0',  # Amazon Linux 2
                'InstanceType': 't3.micro',
                'KeyName': 'my-key-pair',
                'SecurityGroupIds': [self.security_group_id],
                'UserData': user_data,
                'TagSpecifications': [
                    {
                        'ResourceType': 'instance',
                        'Tags': [
                            {'Key': 'Name', 'Value': 'web-app-instance'},
                            {'Key': 'Environment', 'Value': 'production'}
                        ]
                    }
                ]
            }
        )

        print("启动模板创建完成")
        return template_response['LaunchTemplate']['LaunchTemplateId']

    def create_load_balancer(self):
        """创建负载均衡器"""
        print("创建负载均衡器...")

        # 创建目标组
        target_group_response = self.elbv2.create_target_group(
            Name='web-app-targets',
            Protocol='HTTP',
            Port=80,
            VpcId=self.vpc_id,
            HealthCheckPath='/',
            HealthCheckIntervalSeconds=30,
            HealthCheckTimeoutSeconds=5,
            HealthyThresholdCount=3,
            UnhealthyThresholdCount=2
        )
        self.target_group_arn = target_group_response['TargetGroups'][0]['TargetGroupArn']

        # 创建负载均衡器
        lb_response = self.elbv2.create_load_balancer(
            Name='web-app-lb',
            Subnets=self.subnet_ids,
            SecurityGroups=[self.security_group_id],
            Scheme='internet-facing',
            Type='application',
            IpAddressType='ipv4'
        )
        self.load_balancer_arn = lb_response['LoadBalancers'][0]['LoadBalancerArn']

        # 等待负载均衡器可用
        waiter = self.elbv2.get_waiter('load_balancer_available')
        waiter.wait(LoadBalancerArns=[self.load_balancer_arn])

        # 创建监听器
        self.elbv2.create_listener(
            LoadBalancerArn=self.load_balancer_arn,
            Protocol='HTTP',
            Port=80,
            DefaultActions=[
                {
                    'Type': 'forward',
                    'TargetGroupArn': self.target_group_arn
                }
            ]
        )

        print(f"负载均衡器创建完成: {self.load_balancer_arn}")

    def create_auto_scaling_group(self, launch_template_id):
        """创建自动扩缩容组"""
        print("创建自动扩缩容组...")

        self.autoscaling.create_auto_scaling_group(
            AutoScalingGroupName='web-app-asg',
            LaunchTemplate={
                'LaunchTemplateId': launch_template_id,
                'Version': '$Latest'
            },
            MinSize=2,
            MaxSize=6,
            DesiredCapacity=2,
            VPCZoneIdentifier=','.join(self.subnet_ids),
            TargetGroupARNs=[self.target_group_arn],
            HealthCheckType='ELB',
            HealthCheckGracePeriod=300,
            DefaultInstanceWarmup=300,
            Tags=[
                {
                    'Key': 'Name',
                    'Value': 'web-app-instance',
                    'PropagateAtLaunch': True
                },
                {
                    'Key': 'Environment',
                    'Value': 'production',
                    'PropagateAtLaunch': True
                }
            ]
        )

        # 创建扩缩容策略
        self.autoscaling.put_scaling_policy(
            AutoScalingGroupName='web-app-asg',
            PolicyName='scale-out-policy',
            PolicyType='SimpleScaling',
            AdjustmentType='ChangeInCapacity',
            ScalingAdjustment=1,
            Cooldown=300
        )

        self.autoscaling.put_scaling_policy(
            AutoScalingGroupName='web-app-asg',
            PolicyName='scale-in-policy',
            PolicyType='SimpleScaling',
            AdjustmentType='ChangeInCapacity',
            ScalingAdjustment=-1,
            Cooldown=300
        )

        print("自动扩缩容组创建完成")

    def create_s3_bucket(self):
        """创建S3存储桶"""
        print("创建S3存储桶...")

        bucket_name = f'web-app-static-{int(time.time())}'

        self.s3.create_bucket(
            Bucket=bucket_name,
            CreateBucketConfiguration={
                'LocationConstraint': self.region
            }
        )

        # 设置存储桶策略
        bucket_policy = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Sid": "PublicReadGetObject",
                    "Effect": "Allow",
                    "Principal": "*",
                    "Action": "s3:GetObject",
                    "Resource": f"arn:aws:s3:::{bucket_name}/*"
                }
            ]
        }

        self.s3.put_bucket_policy(
            Bucket=bucket_name,
            Policy=json.dumps(bucket_policy)  # json.dumps将Python对象转为JSON字符串
        )

        # 启用版本控制
        self.s3.put_bucket_versioning(
            Bucket=bucket_name,
            VersioningConfiguration={
                'Status': 'Enabled'
            }
        )

        # 配置生命周期规则
        lifecycle_config = {
            'Rules': [
                {
                    'Id': 'DeleteOldVersions',
                    'Status': 'Enabled',
                    'NoncurrentVersionExpiration': {'NoncurrentDays': 30}
                }
            ]
        }

        self.s3.put_bucket_lifecycle_configuration(
            Bucket=bucket_name,
            LifecycleConfiguration=lifecycle_config
        )

        print(f"S3存储桶创建完成: {bucket_name}")
        return bucket_name

    def create_rds_instance(self):
        """创建RDS数据库实例"""
        print("创建RDS数据库实例...")

        # 创建子网组
        subnet_group_name = 'web-app-db-subnet-group'
        self.rds.create_db_subnet_group(
            DBSubnetGroupName=subnet_group_name,
            DBSubnetGroupDescription='Subnet group for web app database',
            SubnetIds=self.subnet_ids[:2]  # 切片操作:[start:end:step]提取子序列
        )

        # 创建数据库实例
        # ⚠️ 安全警告:以下代码示例包含硬编码密码,仅用于演示目的。
        # 在生产环境中,请务必使用环境变量或密钥管理服务(如 AWS Secrets Manager、Azure Key Vault 等)来存储敏感信息。
        db_response = self.rds.create_db_instance(
            DBName='webapp',
            DBInstanceIdentifier='web-app-db',
            DBInstanceClass='db.t3.micro',
            Engine='mysql',
            MasterUsername='admin',
            MasterUserPassword='SecurePassword123!',
            AllocatedStorage=20,
            StorageType='gp2',
            VpcSecurityGroupIds=[self.security_group_id],
            DBSubnetGroupName=subnet_group_name,
            BackupRetentionPeriod=7,
            MultiAZ=False,
            PubliclyAccessible=False,
            Tags=[
                {
                    'Key': 'Name',
                    'Value': 'web-app-database'
                },
                {
                    'Key': 'Environment',
                    'Value': 'production'
                }
            ]
        )

        print(f"RDS实例创建中: {db_response['DBInstance']['DBInstanceIdentifier']}")
        return db_response['DBInstance']['DBInstanceIdentifier']

    def create_cloudfront_distribution(self, s3_bucket_name):
        """创建CloudFront分发"""
        print("创建CloudFront分发...")

        # 获取S3存储桶的Origin ID
        origin_id = f'S3-{s3_bucket_name}'

        distribution_config = {
            'CallerReference': str(int(time.time())),
            'Comment': 'CloudFront distribution for web app',
            'DefaultCacheBehavior': {
                'TargetOriginId': origin_id,
                'ViewerProtocolPolicy': 'allow-all',
                'AllowedMethods': {
                    'Quantity': 2,
                    'Items': ['GET', 'HEAD'],
                    'CachedMethods': {
                        'Quantity': 2,
                        'Items': ['GET', 'HEAD']
                    }
                },
                'ForwardedValues': {
                    'QueryString': False,
                    'Cookies': {'Forward': 'none'}
                },
                'MinTTL': 0,
                'DefaultTTL': 86400,
                'MaxTTL': 31536000
            },
            'Origins': {
                'Quantity': 1,
                'Items': [
                    {
                        'Id': origin_id,
                        'DomainName': f'{s3_bucket_name}.s3.amazonaws.com',
                        'S3OriginConfig': {
                            'OriginAccessIdentity': ''
                        }
                    }
                ]
            },
            'Enabled': True,
            'DefaultRootObject': 'index.html',
            'PriceClass': 'PriceClass_All'
        }

        distribution_response = self.cloudfront.create_distribution(
            DistributionConfig=distribution_config
        )

        distribution_id = distribution_response['Distribution']['Id']
        domain_name = distribution_response['Distribution']['DomainName']

        print(f"CloudFront分发创建完成: {distribution_id}")
        print(f"域名: {domain_name}")

        return distribution_id, domain_name

    def deploy(self):
        """部署完整应用"""
        print("开始部署云端Web应用...")
        print("=" * 50)

        try:  # try/except捕获异常
            # 1. 创建VPC
            self.create_vpc()
            time.sleep(2)

            # 2. 创建安全组
            self.create_security_group()
            time.sleep(2)

            # 3. 创建启动模板
            launch_template_id = self.create_launch_template()
            time.sleep(2)

            # 4. 创建负载均衡器
            self.create_load_balancer()
            time.sleep(5)

            # 5. 创建自动扩缩容组
            self.create_auto_scaling_group(launch_template_id)
            time.sleep(10)

            # 6. 创建S3存储桶
            s3_bucket_name = self.create_s3_bucket()
            time.sleep(2)

            # 7. 创建RDS实例
            db_instance_id = self.create_rds_instance()
            time.sleep(2)

            # 8. 创建CloudFront分发
            distribution_id, domain_name = self.create_cloudfront_distribution(s3_bucket_name)

            print("\n" + "=" * 50)
            print("部署完成!")
            print("=" * 50)
            print(f"VPC ID: {self.vpc_id}")
            print(f"安全组 ID: {self.security_group_id}")
            print(f"负载均衡器 ARN: {self.load_balancer_arn}")
            print(f"自动扩缩容组: web-app-asg")
            print(f"S3存储桶: {s3_bucket_name}")
            print(f"RDS实例: {db_instance_id}")
            print(f"CloudFront域名: {domain_name}")
            print("\n请等待几分钟让所有资源启动完成...")

            return {
                'vpc_id': self.vpc_id,
                'security_group_id': self.security_group_id,
                'load_balancer_arn': self.load_balancer_arn,
                's3_bucket_name': s3_bucket_name,
                'db_instance_id': db_instance_id,
                'cloudfront_domain': domain_name
            }

        except Exception as e:
            print(f"部署失败: {e}")
            raise

if __name__ == '__main__':
    # 部署应用
    app = CloudWebApp(region='us-east-1')
    result = app.deploy()

    print("\n部署信息已保存,请妥善保管!")

1.8 练习题

基础题

  1. 选择题
  2. 以下哪个不是云计算的五大特征?

    • A. 按需自助服务
    • B. 资源池化
    • C. 快速弹性
    • D. 单点故障
  3. IaaS、PaaS、SaaS中,用户管理复杂度最高的是?

    • A. IaaS
    • B. PaaS
    • C. SaaS
    • D. 相同
  4. 简答题

  5. 简述公有云、私有云、混合云的区别和适用场景。
  6. 解释云计算的共享责任模型。

进阶题

  1. 设计题
  2. 设计一个适用于电商平台的云架构,要求:

    • 高可用性
    • 自动扩缩容
    • 数据安全
    • 成本优化
  3. 实践题

  4. 使用AWS SDK创建一个包含EC2、S3、RDS的完整应用架构。

答案

1. 选择题答案

  1. D(单点故障不是云计算特征,云计算强调高可用性)
  2. A(IaaS需要用户管理操作系统和中间件,复杂度最高)

2. 简答题答案

公有云、私有云、混合云的区别:

特性 公有云 私有云 混合云
所有权 第三方提供商 企业自己拥有 结合两者
安全性 较低 最高 中等
成本 按需付费 前期投资大 适中
灵活性 中等
适用场景 初创企业、波动性业务 金融、医疗等监管行业 渐进式云迁移

共享责任模型: - 云服务商负责:物理安全、网络基础设施、虚拟化层 - 用户负责:数据安全、操作系统、应用、配置 - 不同服务模型的责任划分不同

3. 设计题答案

电商平台云架构设计:

Text Only
┌─────────────┐
│   用户      │
└──────┬──────┘
┌──────▼──────┐
│  CloudFront │
│    (CDN)    │
└──────┬──────┘
┌──────▼──────┐
│   WAF       │
│ (Web防火墙)  │
└──────┬──────┘
┌──────▼──────┐
│    ALB      │
│ (负载均衡)  │
└──────┬──────┘
┌──────▼──────┐
│ Auto Scaling│
│   Group     │
└──────┬──────┘
┌──────▼──────┐
│  EC2集群    │
│ (Web服务器) │
└──────┬──────┘
┌──────▼──────┐
│  ElastiCache│
│   (缓存)    │
└─────────────┘
┌──────▼──────┐
│   RDS集群   │
│  (数据库)   │
└─────────────┘

关键设计要点: 1. 使用多可用区部署保证高可用 2. 自动扩缩容应对流量高峰 3. CDN加速静态资源访问 4. WAF防护Web攻击 5. 数据库读写分离和主从复制 6. 使用预留实例优化成本

4. 实践题答案

参见1.7节的完整实现代码。

1.9 面试准备

大厂面试题

字节跳动

  1. 解释IaaS、PaaS、SaaS的区别,并举例说明。
  2. 如何设计一个高可用的云架构?
  3. 云计算的成本优化策略有哪些?
  4. 解释云计算的共享责任模型。

腾讯云

  1. 公有云、私有云、混合云的优缺点是什么?
  2. 如何保证云上数据安全?
  3. 云计算的发展趋势是什么?
  4. 如何选择合适的云服务提供商?

阿里云

  1. 云计算的核心价值是什么?
  2. 如何进行云迁移?
  3. 云计算在AI领域的应用有哪些?
  4. 如何监控和优化云成本?

系统设计题

题目:设计一个支持千万级用户的在线教育平台

要求: - 支持直播课程和点播课程 - 实时互动(弹幕、聊天) - 高并发访问 - 数据安全 - 成本优化

参考答案要点: 1. 使用CDN加速视频内容 2. 使用Serverless处理弹幕和聊天 3. 使用自动扩缩容应对流量高峰 4. 使用多区域部署提高可用性 5. 数据加密和访问控制 6. 使用预留实例和Spot实例优化成本

📚 参考资料

🎯 本章小结

本章深入讲解了云计算的基础知识,包括:

  1. 云计算的定义、特点和核心价值
  2. IaaS、PaaS、SaaS三种服务模型
  3. 公有云、私有云、混合云、多云四种部署模型
  4. 主流云平台(AWS、Azure、GCP、阿里云、腾讯云)
  5. 云计算计费和成本优化策略
  6. 云计算安全基础
  7. 完整的云端Web应用实战案例

通过本章学习,你建立了对云计算的全面理解,为后续学习Docker、Kubernetes和DevOps实践打下了坚实基础。下一章将深入学习Docker容器化技术。