iT邦幫忙

2023 iThome 鐵人賽

DAY 15
0
Cloud Native

AWS AI交易室實戰系列 第 15

Day 15 - AWS ECS & Fargate

  • 分享至 

  • xImage
  •  

提醒一下,今天用到的 AWS 服務是要收費的唷!
AWS Fargate 費用

練習的過程總花費不到 0.5 美金,用完記得清理

Amazon Elastic Container Service (Amazon ECS) 是一項全受管的容器協同運作服務,可簡化容器化應用程式的部署、管理和擴展。 只需描述您的應用程式和所需資源,Amazon ECS 就會跨彈性運算選項啟動、監控和擴展您的應用程式,並自動整合應用程式所需的其他支援AWS 服務。 ~ by AWS ~

AWS Fargate 是一項技術,可以與 Amazon ECS 搭配使用以執行容器,而不需管理 Amazon EC2 執行個體的伺服器或叢集。使用 Fargate,就不再需要佈建、設定或擴展虛擬機器的叢集來執行容器。這樣一來即無須選擇伺服器類型、決定何時擴展叢集,或最佳化叢集壓縮。~ by AWS ~

ECS 是 AWS 容器服務,而直接不用管 EC2 的服務就是 Fargate,事實上 Fargate 只是 ECS 部署服務或是任務時候的一個選項而已(目前只能選 EC2 or Fargate)

這邊先介紹三個名詞概念:
Cluster (叢集):任務或服務的邏輯分組。
Task Definition:一個工作定義是您應用程式的藍圖。它是 JSON 格式的文本文件,用於描述參數以及形成應用程序的一個或多個容器。

首先先建立所需要的 service-role

$ aws iam create-role \       
--role-name ecsTaskExecutionRole \
--assume-role-policy-document file://Day13/ecs-tasks-trust-policy.json

$ aws iam attach-role-policy \                                                    
--role-name ecsTaskExecutionRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy

$ aws iam attach-role-policy \                                                    
--role-name ecsTaskExecutionRole \
--policy-arn arn:aws:iam::aws:policy/CloudWatchFullAccess

$ aws iam get-role \
    --role-name ecsTaskExecutionRole

{
    "Role": {
        ...
        "Arn": <role-arn>,
        "CreateDate": "2023-09-16T16:48:49+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",

用上面產生的

$ aws ecs create-cluster --cluster-name marathon-fargate-cluster

$ aws ecs register-task-definition --cli-input-json file://Day13/marathon-fargate-task.json
# marathon-fargate-task.json
{
        "family": "marathon-fargate-task",
        "networkMode": "awsvpc",
        "taskRoleArn": <role-arn>, 
        "containerDefinitions": [
            {
                "name": "fargate-app",
                "image": "public.ecr.aws/docker/library/httpd:latest",
                "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"
}

$ aws ecs list-task-definitions
{
    "taskDefinitionArns": [
        "arn:aws:ecs:ap-northeast-1:411932542528:task-definition/marathon-fargate-task:1"
    ]
}

接著我們建立 service,注意這裡需要選擇 public subnet,security group 要選 inbound rule 有 80 port source anywhere,加上 --enable-execute-command 讓我們待會可直接用 shell 連線進去

$ aws ecs create-service \
--cluster marathon-fargate-cluster \
--service-name marathon-fargate-service \
--task-definition marathon-fargate-task:1 \
--desired-count 1 --launch-type "FARGATE" \
--enable-execute-command \
--network-configuration "awsvpcConfiguration={subnets=[<subnet-id>],securityGroups=[<security-group-id>],assignPublicIp=ENABLED}"

//check if successful
$ aws ecs describe-services \
--cluster marathon-fargate-cluster \
--services marathon-fargate-service

接著我們需要查詢建立的 Task 公有 ip 是多少

$ aws ecs list-tasks \
--cluster marathon-fargate-cluster \
--service marathon-fargate-service

$ aws ecs describe-tasks --cluster fargate-cluster --tasks <task-arn>
{
    "tasks": [
        {
            "attachments": [
                {
                    "id": "d9e7735a-16aa-4128-bc7a-b2d5115029e9",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                       ...
                        {
                            "name": "networkInterfaceId",
                            "value": <eni-id>
                        },
                    ]
                }
…
}

$ aws ec2 describe-network-interfaces --network-interface-id <eni-id>

在瀏覽器打網址,成功!
success!

如果想要直接連進去 Container 需要透過 ECS Exec 需要進行以下步驟:

  1. 安裝 AWS CLI
  2. 安裝 Session Manager Plugin for the AWS CLI
    1. curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/mac_arm64/sessionmanager-bundle.zip" -o "sessionmanager-bundle.zip"
    2. unzip sessionmanager-bundle.zip
    3. sudo ./sessionmanager-bundle/install -i /usr/local/sessionmanagerplugin -b /usr/local/bin/session-manager-plugin
  3. 在 task role 上面加上以下的 policy,需要先建立 policy 然後再 attach 上去
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssmmessages:CreateControlChannel",
                "ssmmessages:CreateDataChannel",
                "ssmmessages:OpenControlChannel",
                "ssmmessages:OpenDataChannel"
            ],
            "Resource": "*"
        }
    ]
}

最後下指令連進去:

$ aws ecs execute-command \
--cluster marathon-fargate-cluster \
--task <task-arn>  \
--container  fargate-app \
--interactive \
--command "/bin/sh"

# apt update
# apt install curl
# curl <private-ip>
<html>
    <head> 
     <title>Amazon ECS Sample App</title> 
    ...
</html>

用完後別忘了清理唷:

$ aws ecs delete-service \
--cluster marathon-fargate-cluster \
--service marathon-fargate-service --force

$ aws ecs delete-cluster \
--cluster marathon-fargate-cluster

隨著容器的普及化,使用 ECS 取代 EC2 已經是個趨勢了,ECS & Fargate 因為是全受管服務的關係,設定有點繁雜 & 不太直觀,希望藉由此次的練習可以讓各位快速上手這個架構在 AWS 上面的容器服務

參考資料:

https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_AWSCLI_Fargate.html
https://medium.com/@chihsuan/aws-ec2-container-service-%E6%A6%82%E5%BF%B5%E8%88%87%E4%BD%BF%E7%94%A8%E4%BB%8B%E7%B4%B9-28258247947a


上一篇
Day 14 - AWS Lambda Extensions 實作
下一篇
Day 16 - AWS API Gateway & Dynamo DB
系列文
AWS AI交易室實戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言