Amazon Elastic Container Service
开发人员指南 (API 版本 2014-11-13)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

教程:使用 Service Discovery 创建服务

Service discovery 已集成到 Amazon ECS 控制台的创建服务向导中。有关更多信息,请参阅创建服务

以下教程说明如何创建一个包含 Fargate 任务的 ECS 服务,该任务将 service discovery 与 AWS CLI 结合使用。

注意

只有以下区域支持 Fargate 任务:

Region Name Region
US East (N. Virginia) us-east-1
US East (Ohio) us-east-2
US West (N. California) us-west-1
US West (Oregon) us-west-2
Asia Pacific (Mumbai) ap-south-1
EU (Ireland) eu-west-1
EU (London) eu-west-2
EU (Frankfurt) eu-central-1
Asia Pacific (Tokyo) ap-northeast-1
Canada (Central) ca-central-1
Asia Pacific (Seoul) ap-northeast-2
Asia Pacific (Singapore) ap-southeast-1
Asia Pacific (Sydney) ap-southeast-2

先决条件

本教程假设以下先决条件已完成:

步骤 1:创建Service Discovery资源

使用以下步骤创建您的service discovery命名空间和service discovery服务。

创建Service Discovery资源

  1. 在现有 VPC 之一中创建一个名为 tutorial 的私有service discovery命名空间:

    aws servicediscovery create-private-dns-namespace --name tutorial --vpc vpc-abcd1234 --region us-east-1

    输出:

    {
        "OperationId": "h2qe3s6dxftvvt7riu6lfy2f6c3jlhf4-je6chs2e"
    }
  2. 使用来自之前输出的 OperationId,验证已成功创建私有命名空间。复制命名空间 ID,因为在后续命令中会使用它。

    aws servicediscovery get-operation --operation-id h2qe3s6dxftvvt7riu6lfy2f6c3jlhf4-je6chs2e

    输出:

    {
        "Operation": {
            "Id": "h2qe3s6dxftvvt7riu6lfy2f6c3jlhf4-je6chs2e",
            "Type": "CREATE_NAMESPACE",
            "Status": "SUCCESS",
            "CreateDate": 1519777852.502,
            "UpdateDate": 1519777856.086,
            "Targets": {
                "NAMESPACE": "ns-uejictsjen2i4eeg"
            }
        }
    }
  3. 通过使用先前输出中的 NAMESPACE ID 来创建一个名为 myapplication 的服务发现服务。复制service discovery服务 ID,因为在后续命令中会使用它:

    aws servicediscovery create-service --name myapplication --dns-config 'NamespaceId="ns-uejictsjen2i4eeg",DnsRecords=[{Type="A",TTL="300"}]' --health-check-custom-config FailureThreshold=1 --region us-east-1

    输出:

    {
        "Service": {
            "Id": "srv-utcrh6wavdkggqtk",
            "Arn": "arn:aws:servicediscovery:region:aws_account_id:service/srv-utcrh6wavdkggqtk",
            "Name": "myapplication",
            "DnsConfig": {
                "NamespaceId": "ns-uejictsjen2i4eeg",
                "DnsRecords": [
                    {
                        "Type": "A",
                        "TTL": 300
                    }
                ]
            },
            "HealthCheckCustomConfig": {
                "FailureThreshold": 1
            },
            "CreatorRequestId": "e49a8797-b735-481b-a657-b74d1d6734eb"
        }
    }

步骤 2:创建 Amazon ECS 资源

使用以下步骤创建您的 Amazon ECS 集群、任务定义和服务。

创建 Amazon ECS 资源

  1. 创建要使用的名为 tutorial 的 Amazon ECS 集群:

    aws ecs create-cluster --cluster-name tutorial --region us-east-1

    输出:

    {
        "cluster": {
            "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/tutorial",
            "clusterName": "tutorial",
            "status": "ACTIVE",
            "registeredContainerInstancesCount": 0,
            "runningTasksCount": 0,
            "pendingTasksCount": 0,
            "activeServicesCount": 0,
            "statistics": []
        }
    }
  2. 注册与 Fargate 兼容的任务定义。它需要使用 awsvpc 网络模式。以下为用于本教程的示例任务定义。

    首先,使用以下任务定义的内容创建名为 fargate-task.json 的文件:

    { "family": "tutorial-task-def", "networkMode": "awsvpc", "containerDefinitions": [ { "name": "sample-app", "image": "httpd:2.4", "portMappings": [ { "containerPort": 80, "hostPort": 80, "protocol": "tcp" } ], "essential": true, "entryPoint": [ "sh", "-c" ], "command": [ "/bin/sh -c \"echo '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div></body></html>' > /usr/local/apache2/htdocs/index.html && httpd-foreground\"" ] } ], "requiresCompatibilities": [ "FARGATE" ], "cpu": "256", "memory": "512" }

    然后,使用您创建的 fargate-task.json 文件注册任务定义:

    aws ecs register-task-definition --cli-input-json file://fargate-task.json --region us-east-1
  3. 使用您将要创建的 ECS 服务的内容创建名为 ecs-service-discovery.json 的文件。本示例使用在上一步中创建的任务定义。由于示例任务定义使用 awsvpc 网络模式,awsvpcConfiguration 是必需的。

    { "cluster": "tutorial", "serviceName": "ecs-service-discovery", "taskDefinition": "tutorial-task-def", "serviceRegistries": [ { "registryArn": "arn:aws:servicediscovery:region:aws_account_id:service/srv-utcrh6wavdkggqtk" } ], "launchType": "FARGATE", "platformVersion": "1.1.0", "networkConfiguration": { "awsvpcConfiguration": { "assignPublicIp": "ENABLED", "securityGroups": [ "sg-abcd1234" ], "subnets": [ "subnet-abcd1234" ] } }, "desiredCount": 1 }

    创建 ECS 服务,指定 Fargate 启动类型和 1.1.0 平台版本,它将使用service discovery:

    aws ecs create-service --cli-input-json file://ecs-service-discovery.json --region us-east-1

    输出:

    {
        "service": {
            "serviceArn": "arn:aws:ecs:region:aws_account_id:service/ecs-service-discovery",
            "serviceName": "ecs-service-discovery",
            "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/tutorial",
            "loadBalancers": [],
            "serviceRegistries": [
                {
                    "registryArn": "arn:aws:servicediscovery:region:aws_account_id:service/srv-utcrh6wavdkggqtk"
                }
            ],
            "status": "ACTIVE",
            "desiredCount": 1,
            "runningCount": 0,
            "pendingCount": 0,
            "launchType": "FARGATE",
            "platformVersion": "1.1.0",
            "taskDefinition": "arn:aws:ecs:region:aws_account_id:task-definition/tutorial-task-def:1",
            "deploymentConfiguration": {
                "maximumPercent": 200,
                "minimumHealthyPercent": 100
            },
            "deployments": [
                {
                    "id": "ecs-svc/9223370516993140842",
                    "status": "PRIMARY",
                    "taskDefinition": "arn:aws:ecs:region:aws_account_id:task-definition/tutorial-task-def:1",
                    "desiredCount": 1,
                    "pendingCount": 0,
                    "runningCount": 0,
                    "createdAt": 1519861634.965,
                    "updatedAt": 1519861634.965,
                    "launchType": "FARGATE",
                    "platformVersion": "1.1.0",
                    "networkConfiguration": {
                        "awsvpcConfiguration": {
                            "subnets": [
                                "subnet-abcd1234"
                            ],
                            "securityGroups": [
                                "sg-abcd1234"
                            ],
                            "assignPublicIp": "ENABLED"
                        }
                    }
                }
            ],
            "roleArn": "arn:aws:iam::aws_account_id:role/ECSServiceLinkedRole",
            "events": [],
            "createdAt": 1519861634.965,
            "placementConstraints": [],
            "placementStrategy": [],
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-abcd1234"
                    ],
                    "securityGroups": [
                        "sg-abcd1234"
                    ],
                    "assignPublicIp": "ENABLED"
                }
            }
        }
    }

步骤 3:验证Service Discovery

您可以通过查询您的service discovery信息来验证是否正确创建了所有内容。配置service discovery之后,可以使用 AWS Cloud Map API 操作或者在 VPC 中使用 dig 来查询,如下所述。

验证服务发现配置

  1. 通过使用 service discovery 服务 ID,列出 service discovery 实例:

    aws servicediscovery list-instances --service-id srv-utcrh6wavdkggqtk --region us-east-1

    输出:

    {
        "Instances": [
            {
                "Id": "16becc26-8558-4af1-9fbd-f81be062a266",
                "Attributes": {
                    "AWS_INSTANCE_IPV4": "172.31.87.2"
                    "AWS_INSTANCE_PORT": "80", 
                    "AVAILABILITY_ZONE": "us-east-1a", 
                    "REGION": "us-east-1", 
                    "ECS_SERVICE_NAME": "ecs-service-discovery", 
                    "ECS_CLUSTER_NAME": "tutorial", 
                    "ECS_TASK_DEFINITION_FAMILY": "tutorial-task-def"
                }
            }
        ]
    }
  2. 通过service discovery命名空间和服务,使用其他参数来查询有关service discovery实例的详细信息:

    aws servicediscovery discover-instances --namespace-name tutorial --service-name myapplication --query-parameters ECS_CLUSTER_NAME=tutorial

    输出:

    {
        "Instances": [
            {
                "InstanceId": "16becc26-8558-4af1-9fbd-f81be062a266", 
                "NamespaceName": "tutorial", 
                "ServiceName": "ecs-service-discovery", 
                "HealthStatus": "HEALTHY", 
                "Attributes": {
                    "AWS_INSTANCE_IPV4": "172.31.87.2"
                    "AWS_INSTANCE_PORT": "80", 
                    "AVAILABILITY_ZONE": "us-east-1a", 
                    "REGION": "us-east-1", 
                    "ECS_SERVICE_NAME": "ecs-service-discovery", 
                    "ECS_CLUSTER_NAME": "tutorial", 
                    "ECS_TASK_DEFINITION_FAMILY": "tutorial-task-def"
                }
            }
        ]
    }
  3. 在 Route 53 托管区域中为service discovery服务创建的 DNS 记录可以使用以下 AWS CLI 命令查询。

    使用命名空间 ID 获取有关命名空间的信息,其中包括 Route 53 托管区域 ID:

    aws servicediscovery get-namespace --id ns-uejictsjen2i4eeg --region us-east-1

    输出:

    {
        "Namespace": {
            "Id": "ns-uejictsjen2i4eeg",
            "Arn": "arn:aws:servicediscovery:region:aws_account_id:namespace/ns-uejictsjen2i4eeg",
            "Name": "tutorial",
            "Type": "DNS_PRIVATE",
            "Properties": {
                "DnsProperties": {
                    "HostedZoneId": "Z35JQ4ZFDRYPLV"
                }
            },
            "CreateDate": 1519777852.502,
            "CreatorRequestId": "9049a1d5-25e4-4115-8625-96dbda9a6093"
        }
    }
  4. 使用 Route 53 托管区域 ID 获取托管区域的资源记录集:

    aws route53 list-resource-record-sets --hosted-zone-id Z35JQ4ZFDRYPLV --region us-east-1

    输出:

    {
        "ResourceRecordSets": [
            {
                "Name": "tutorial.",
                "Type": "NS",
                "TTL": 172800,
                "ResourceRecords": [
                    {
                        "Value": "ns-1536.awsdns-00.co.uk."
                    },
                    {
                        "Value": "ns-0.awsdns-00.com."
                    },
                    {
                        "Value": "ns-1024.awsdns-00.org."
                    },
                    {
                        "Value": "ns-512.awsdns-00.net."
                    }
                ]
            },
            {
                "Name": "tutorial.",
                "Type": "SOA",
                "TTL": 900,
                "ResourceRecords": [
                    {
                        "Value": "ns-1536.awsdns-00.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400"
                    }
                ]
            },
            {
                "Name": "myapplication.tutorial.",
                "Type": "A",
                "SetIdentifier": "16becc26-8558-4af1-9fbd-f81be062a266",
                "MultiValueAnswer": true,
                "TTL": 300,
                "ResourceRecords": [
                    {
                        "Value": "172.31.87.2"
                    }
                ]
            }
        ]
    }
  5. 您还可以使用 dig,从您 VPC 中的实例通过以下命令查询 DNS:

    dig +short myapplication.tutorial

    输出:

    172.31.87.2

步骤 4:清除

完成本教程后,您应清除相关资源,以避免产生与未使用的资源相关的费用。

清除服务发现实例和 Amazon ECS 资源

  1. 取消注册service discovery服务实例:

    aws servicediscovery deregister-instance --service-id srv-utcrh6wavdkggqtk --instance-id 16becc26-8558-4af1-9fbd-f81be062a266 --region us-east-1

    输出:

    {
        "OperationId": "xhu73bsertlyffhm3faqi7kumsmx274n-jh0zimzv"
    }
  2. 通过使用先前输出中的 OperationId,验证service discovery服务实例是否已成功取消注册:

    aws servicediscovery get-operation --operation-id xhu73bsertlyffhm3faqi7kumsmx274n-jh0zimzv --region us-east-1

    输出:

    {
        "Operation": {
            "Id": "xhu73bsertlyffhm3faqi7kumsmx274n-jh0zimzv",
            "Type": "DEREGISTER_INSTANCE",
            "Status": "SUCCESS",
            "CreateDate": 1525984073.707,
            "UpdateDate": 1525984076.426,
            "Targets": {
                "INSTANCE": "16becc26-8558-4af1-9fbd-f81be062a266",
                "ROUTE_53_CHANGE_ID": "C5NSRG1J4I1FH",
                "SERVICE": "srv-utcrh6wavdkggqtk"
            }
        }
    }
  3. 删除service discovery服务:

    aws servicediscovery delete-service --id srv-utcrh6wavdkggqtk --region us-east-1
  4. 删除service discovery命名空间:

    aws servicediscovery delete-namespace --id ns-uejictsjen2i4eeg --region us-east-1

    输出:

    {
        "OperationId": "c3ncqglftesw4ibgj5baz6ktaoh6cg4t-jh0ztysj"
    }
  5. 通过使用先前输出中的 OperationId,验证service discovery命名空间是否已成功删除:

    aws servicediscovery get-operation --operation-id c3ncqglftesw4ibgj5baz6ktaoh6cg4t-jh0ztysj --region us-east-1

    输出:

    {
        "Operation": {
            "Id": "c3ncqglftesw4ibgj5baz6ktaoh6cg4t-jh0ztysj",
            "Type": "DELETE_NAMESPACE",
            "Status": "SUCCESS",
            "CreateDate": 1525984602.211,
            "UpdateDate": 1525984602.558,
            "Targets": {
                "NAMESPACE": "ns-rymlehshst7hhukh",
                "ROUTE_53_CHANGE_ID": "CJP2A2M86XW3O"
            }
        }
    }
  6. 更新 Amazon ECS 服务,使预期数量为 0,从而允许您删除它:

    aws ecs update-service --cluster tutorial --service ecs-service-discovery --desired-count 0 --force-new-deployment --region us-east-1
  7. 删除Amazon ECS服务:

    aws ecs delete-service --cluster tutorial --service ecs-service-discovery --region us-east-1
  8. 删除 Amazon ECS 集群:

    aws ecs delete-cluster --cluster tutorial --region us-east-1