AWS Copilot CLI 是一個開源的 CLI ,可以方便地用於管理 AWS App Runner, AWS ECS, AWS Farget.

只要透過簡單的指令就可搭建起 containerized application,

在本文會先介紹 ECS 以及如何透過 Copilot 來部署應用到 ECS 。

AWS ECS 簡介

AWS ECS(Elastic Container Service) 是一個簡單且高擴充的 container cluster 管理服務, 可以透過 task definnition 定義 container 並且直接運行在 serverless infrastructure (Fargate),或者可以選用 EC2 來做更多的調控。

下方是一個 ECS Object 示意

在開始創建 ECS ,有以下流程

Container definition : 會先需要選擇 image 以及規格 (cpu, RAM….)

Task definition : 用於定義 APP 的藍圖,可以用來描述要部署的一個或多個 containers (最多10 個) ,透過 attributes 設定 container 配置(network, cpu, ram..) 等

Service: 可定義 Cluster 中運行的數量,可以設定是否啟用 Load Balancer (ALB)

Cluster: 定義 Cluster 名稱,VPC, subnet

通常要創建 ECS 有幾種方式可以選用,這裡要介紹的是透過 Copilot 來建立 ECS 應用服務。

透過 AWS Copilot 建立 ECS 服務

Copilot CLI 提供了管理 ECS 的功能,關於 Copilot 可以參考 AWS Copilot CLI 線上文件

接下來說明範例以及較常見的指令,首先,透過下方指令在 Mac 本地安裝 copilot

brew install aws/tap/copilot-cli

其他 Linux, Windows 可以參考 copilot 官方安裝說明

安裝後,查看相關指令

$ copilot help
👩‍✈️ Launch and manage containerized applications on AWS.

Commands
  Getting Started 🌱
    init        Create a new ECS or App Runner application.
    docs        Open the copilot docs.

  Develop ✨
    app         Commands for applications.
                Applications are a collection of services and environments.

    env         Commands for environments.
                Environments are deployment stages shared between services.

    svc         Commands for services.
                Services are long-running ECS or App Runner services.

    job         Commands for jobs.
                Jobs are tasks that are triggered by events.

    task        Commands for tasks.
                One-off Amazon ECS tasks that terminate once their work is done.

  Release 🚀
    pipeline    Commands for pipelines.
                Continuous delivery pipelines to release services.

    deploy      Deploy a Copilot job or service.

  Extend 🧸
    storage     Commands for working with storage and databases.
    secret      Commands for secrets.
                Secrets are sensitive information that you need in your application.

  Settings ⚙️
    version     Print the version number.
    completion  Output shell completion code.

Flags
  -h, --help   help for copilot

Examples
  Displays the help menu for the "init" command.
  `$ copilot init --help`

使用 copilot 部署應用程式相當簡單,準備好 Dockerfile 後,

只要執行下方指令,就會直接幫你建立好 ECR, ECS, Farget, ALB … 整個環境

copilot init --app poc-service                      \
  --name api                                 \
  --type 'Load Balanced Web Service'         \
  --dockerfile './Dockerfile'                \
  --port 80                                  \
  --deploy

說明幾個參數意思:

  • app :表示此應用程式
  • Name: Service 名稱
  • Type: 服務類型,目前支援兩種 Load Balanced Web Service : 為 public network 可讓外部訪問,Backend Service : 為 private 外界無法訪問。
  • dockerfile :指定要部署的 Dockerfile

output

Note: It's best to run this command in the root of your Git repository.
Welcome to the Copilot CLI! We're going to walk you through some questions
to help you get set up with a containerized application on AWS. An application is a collection of
containerized services that operate together.

Ok great, we'll set up a Load Balanced Web Service named api in application poc-service listening on port 80.

✔ Created the infrastructure to manage services and jobs under application poc-service.

✔ The directory copilot will hold service manifests for application poc-service.

✔ Wrote the manifest for service api at copilot/api/manifest.yml
Your manifest contains configurations like your container size and port (:80).

✔ Created ECR repositories for service api.


⠙ Linking account xxxxx and region ap-northeast-1 to application poc-service.

✔ Proposing infrastructure changes for the poc-service-test environment.
- Creating the infrastructure for the poc-service-test environment.      [create complete]  [77.0s]
  - An IAM Role for AWS CloudFormation to manage resources               [create complete]  [19.8s]
  - An ECS cluster to group your services                                [create complete]  [10.7s]
  - An IAM Role to describe resources in your environment                [create complete]  [22.2s]
  - A security group to allow your containers to talk to each other      [create complete]  [6.5s]
  - An Internet Gateway to connect to the public internet                [create complete]  [17.5s]
  - Private subnet 1 for resources with no internet access               [create complete]  [16.2s]
  - Private subnet 2 for resources with no internet access               [create complete]  [16.2s]
  - Public subnet 1 for resources that can access the internet           [create complete]  [16.2s]
  - Public subnet 2 for resources that can access the internet           [create complete]  [16.2s]
  - A Virtual Private Cloud to control networking of your AWS resources  [create complete]  [17.5s]
✔ Created environment test in region ap-northeast-1 under application poc-service.
Environment test is already on the latest version v1.8.0, skip upgrade.
[+] Building 5.7s (9/9) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                            0.3s
 => => transferring dockerfile: 580B                                                                                                                                            0.0s
 => [internal] load .dockerignore                                                                                                                                               0.1s
 => => transferring context: 2B                                                                                                                                                 0.0s
 => [internal] load metadata for docker.io/library/ubuntu:18.04                                                                                                                 4.7s
 => [auth] library/ubuntu:pull token for registry-1.docker.io                                                                                                                   0.0s
 => [1/4] FROM docker.io/library/ubuntu:18.04@sha256:xxxxx                                                           0.0s
 => CACHED [2/4] RUN apt-get update &&  apt-get -y install apache2                                                                                                              0.0s
 => CACHED [3/4] RUN echo 'Hello World!' > /var/www/html/index.html                                                                                                             0.0s
 => CACHED [4/4] RUN echo '. /etc/apache2/envvars' > /root/run_apache.sh &&  echo 'mkdir -p /var/run/apache2' >> /root/run_apache.sh &&  echo 'mkdir -p /var/lock/apache2' >>   0.0s
 => exporting to image                                                                                                                                                          0.0s
 => => exporting layers                                                                                                                                                         0.0s
 => => writing image sha256:xxxxx                                                                                    0.0s
 => => naming to xxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/poc-service/api                                                                                              0.0s

Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
Login Succeeded
Using default tag: latest
The push refers to repository [xxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/poc-service/api]
fbc9855f2658: Pushed
62edf0e82b81: Pushed
ecc09a389dc9: Pushed
40a154bd3352: Pushed
latest: digest: sha256:xxxxx size: 1155
✔ Proposing infrastructure changes for stack poc-service-test-api
- Creating the infrastructure for stack poc-service-test-api                      [create complete]  [322.5s]
  - Service discovery for your services to communicate within the VPC             [create complete]  [2.5s]
  - Update your environment's shared resources                                    [update complete]  [152.4s]
    - A security group for your load balancer allowing HTTP and HTTPS traffic     [create complete]  [5.4s]
    - An Application Load Balancer to distribute public traffic to your services  [create complete]  [120.3s]
  - An IAM Role for the Fargate agent to make AWS API calls on your behalf        [create complete]  [20.4s]
  - A CloudWatch log group to hold your service logs                              [create complete]  [2.5s]
  - An ECS service to run and maintain your tasks in the environment cluster      [create complete]  [59.2s]
    Deployments
               Revision  Rollout      Desired  Running  Failed  Pending
      PRIMARY  1         [completed]  1        1        0       0
  - A target group to connect the load balancer to your service                   [create complete]  [0.0s]
  - An ECS task definition to group your containers and run them on ECS           [create complete]  [2.7s]
  - An IAM role to control permissions for the containers in your tasks           [create complete]  [20.4s]
✔ Deployed service api.
Recommended follow-up action:
  - You can access your service at http://xxxxx.ap-northeast-1.elb.amazonaws.com over the internet.

這裡會建立 ECR poc-service/api

並且在最後會提示可以訪問 service 的位置

✔ Deployed service api.
Recommended follow-up action:
  - You can access your service at http://xxxx.ap-northeast-1.elb.amazonaws.com over the internet.

Copilot manifest.yml

在執行 copilot init 後,在 deploy 完成會在目錄下建立一個 copilot/app名稱/manifest.yml 檔案

裡面就描述了這次部署 ECS的

manifest.yml
# The manifest for the "api" service.
# Read the full specification for the "Load Balanced Web Service" type at:
#  https://aws.github.io/copilot-cli/docs/manifest/lb-web-service/

# Your service name will be used in naming your resources like log groups, ECS services, etc.
name: api
type: Load Balanced Web Service

# Distribute traffic to your service.
http:
  # Requests to this path will be forwarded to your service.
  # To match all requests you can use the "/" path.
  path: '/'
  # You can specify a custom health check path. The default is "/".
  # healthcheck: '/'

# Configuration for your containers and service.
image:
  # Docker build arguments. For additional overrides: https://aws.github.io/copilot-cli/docs/manifest/lb-web-service/#image-build
  build: Dockerfile
  # Port exposed through your container to route traffic to it.
  port: 80

cpu: 256       # Number of CPU units for the task.
memory: 512    # Amount of memory in MiB used by the task.
count: 1       # Number of tasks that should be running in your service.
exec: true     # Enable running commands in your container.

# Optional fields for more advanced use-cases.
#
#variables:                    # Pass environment variables as key value pairs.
#  LOG_LEVEL: info

#secrets:                      # Pass secrets from AWS Systems Manager (SSM) Parameter Store.
#  GITHUB_TOKEN: GITHUB_TOKEN  # The key is the name of the environment variable, the value is the name of the SSM parameter.

# You can override any of the values defined above by environment.
#environments:
#  test:
#    count: 2               # Number of tasks to run for the "test" environment.

Copilot 常用命令說明

初始化 deploy

copilot init

列出目前 AWS Copilot application

copilot app ls

查看 deploy service log

copilot svc logs

查看目前 service 狀態

copilot svc status

刪除 deploy 的項目

copilot app delete

刪除 Copilot 應用

這裡刪除 deploy 項目,同樣只要一個指令就可以把部署的整個環境都移除

copilot app delete

output

Sure? Yes
✔ Deleted service api from environment test.
✔ Deleted resources of service api from application poc-service.

✔ Deleted service api from application poc-service.
✔ Deleted environment test from application poc-service.
✔ Cleaned up deployment resources.
✔ Deleted application resources.
✔ Deleted application configuration.
✔ Deleted local .workspace file.