How to Run a Application on AWS ECS: A Step-by-Step Guide
Xây dựng ECS Cluster EC2 launch type, Build custom nginx app bằng docker và chạy trên ECS Cluster.
by DuyNCT
Dec 2024
On this page
833eb38c-e495-4f2d-84bf-9cf3a5e32bde.png
Xây dựng ECS Cluster EC2 launch type, Build custom nginx app bằng docker và chạy trên ECS Cluster.
Lab Details
- Bài Lab này sẽ hướng dẫn bạn các bước để khởi chạy và configure custom nginx container trên ECS Cluster.
- Duration: 60 minutes
- AWS Region: US East (N. Virginia) us-east-1 Architecture Diagram
40d0069e-7e91-4775-95a2-ffdef9ec156c.png
Task Details
- Create VPC
- Create EC2 đặt ở Public Subnet (Đóng vai trò như là bastion host)
- Create ECR repository and build Docker image
- Create ECS Cluster
- Create Task definition
- Create TG
- Create ALB
- Create ECS Service
- Test hoạt động
- Setting Route53 and access website (optional)
1. Create VPC (VPC + IGW + Subnet + Route Table + NAT)
VPC settings
- Resources to create:
VPC and more - Auto-generate:
check - Name:
d-vpc-002 - IPv4 CIDR block:
10.1.0.0/16 - Number of Availability Zones (AZs) :
2 - Number of public subnets:
2 - Number of private subnets:
2 - NAT gateways ($):
In 1 AZ - VPC endpoints:
S3 Gateway - Còn lại để default
ace9e00a-45d6-4da5-9bbb-f365256f9694.png
2. Create EC2 đặt ở Public Subnet (Đóng vai trò như là bastion host)
Chúng ta cần tạo 1 EC2 cho mục đích build docker image và push lên ECR, việc này có thể thực hiện ở local (Nếu như môi trường local của bạn đã được cài đặt docker)
Bastion host cũng có thể access đến private instance khi cần troubleshooting.
Note: Nếu local đã chạy được docker, có thể bỏ qua step này
2.1 Create Security Group cho Bastion host
-
Name:
d-sg-SAA-basion-host -
Description:
Allow ssh from internet -
VPC:
d-vpc-002-vpc -
Inbound rules
1/1 dòngSSH TCP 22 0.0.0.0/0 -
Outbound rules
1/1 dòngAll traffic All All 0.0.0.0/0 -
Tags
1/1 dòngName d-sg-SAA-basion-host
2.2 Create EC2
- Name:
d-ec2-SAA-bastion-host - OS: Default (Amazon Linux 2023)
- Instance type: Default (t2.micro)
- Key pair:
d-key-SAA-common(Nếu chưa có thì tạo mới) - Network Setting:
- VPC:
d-vpc-002-vpc - Subnet:
d-vpc-002-subnet-public1-us-east-1a - Auto-assign public IP:
Enable - Select existing security group:
d-sg-SAA-basion-host
- VPC:
2.3 Ceate Role SAA-PushImagesToECR-EC2Role for EC2
Để có thể push Docker image đến ECR, chúng ta cần tạo Role và gắn cho EC2
Create Role
- Use case:
EC2 - Permissions policies:
EC2InstanceProfileForImageBuilderECRContainerBuilds - Role name:
SAA-PushImagesToECR-EC2Role
e62c8cbc-2ba0-4c8d-b913-2100259bc9eb.png
Attach to Bastion host
5a24a506-4dbd-4da1-a9d7-6118d4931410.png
2.4 Connect to EC2 and Install Docker
- Connect to EC2
9b1675c0-2705-4c6b-9553-3c0cf96b5ac0.png
-
Install Docker
Bashsudo yum update -y sudo yum -y install docker -
Start Docker
Bashsudo service docker start -
Access Docker commands in ec2-user user
Bashsudo usermod -a -G docker ec2-user sudo chmod 666 /var/run/docker.sock -
docker version
Bashdocker version
0dfe45ad-1ad6-4a46-a3f1-16e512ec48f9.png3. Create ECR repository and build Docker image
3.1 Create ECR Repository
Tại Console của Elastic Container Registry -> Chọn Repositories -> Create repository
f8c19ee0-27b0-4cda-9176-168c50df3282.pngGeneral settings
- Visibility settings: Private
- Repository name:
d-ecr-saa-nginx-custom
31c90de9-34c2-432a-b6b6-295b28051c11.png3.2 Build Docker image
-
Connect to Bastion host (hoặc chạy ở local)
-
Create Custom nginx container
Bashmkdir nginx-app cd nginx-app/ -
Create file
index.htmlindex.html
HTML<!DOCTYPE html> <html><head><title> ECS | CloudmentorPro Blog </title></head><body style =text-align:center;background-color:white;font-weight:900;font-size:20px;font-family:Helvetica,Arial,sans-serif><img src ="https://www.docker.com/wp-content/uploads/2022/03/Moby-logo.png"><h1> Welcome to my custom nginx webpage hosted in a Docker container </h1><p> This container was deployed: <div id ="date"></div></p><script> var date = new Date(); document.getElementById("date").innerHTML=date.toLocaleString(); </script></body></html> -
Create
DockerfileDockerfile
YAMLFROM nginx:1.25.3 COPY index.html /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] -
Build image: nginx-custom
Bashdocker build -t nginx-custom . -
Docker run
Bashdocker run -d --name nginx -p 8080:80 nginx-custom -
Confirm
Bashdocker ps curl localhost:8080
71e6d369-cd77-490b-ad69-89f6fcbfdfe5.pngVậy là chúng ta đã build và test docker image xong. Tiếp theo chúng ta sẽ build và push docker image lên ECR repository
3.3 Connect to Repository
- Tại Console ECR -> Repositories -> Click chọn d-ecr-saa-nginx-custom -> View push commands
d42014c3-2ec5-40a4-94fc-3562e5627468.png- Copy và chạy lần lượt các command
81a65573-168c-40bb-9c28-bc361b9a5ac4.pngcd nginx-app- Copy command ① and run to login
- Copy command ② and run to build image
- Copy command ③ and run to tag image (có thể thay latest ở cuối command bằng một tag khác như: 20231225_1)
- Copy command ④ and run to push image to ECR (chú ý nếu thay latest ở ③ thì cũng thay tương tự ở command này: 20231225_1)
Note: mỗi lần update application chúng ta sẽ tạo ra 1 docker image với tag khác nhau, và để có thể nhanh chóng roll back về image trước đó, nên việc đặt tag riêng lẻ cho các phiên bản application được recommend.
Confirm image had pushed to ECR
4227d446-9474-42a8-93fa-762fa6ad489e.png4. Create ECS Cluster
Vào Console Elastic Container Service -> Chọn Cluster -> Create cluster
ad6b00b5-4aac-4cce-b30d-fc020976c918.png- Cluster configuration
- Cluster name:
d-ecs-SAA-{yourname}-cluster01Nhớ thay tên của mình vào chổ {yourname} vì Cluster name không được trùng nhau trong cùng Region
- Cluster name:
- Infrastructure
- Amazon EC2 instances:
Checked - Auto Scaling group (ASG): Create new ASG
- Operating system/Architecture: Amazon Linux 2023
- EC2 instance type: t3.medium
- Desired capacity
- Minimum: 2
- Maximum: 2
- SSH Key pair: d-key-SAA-common
- Amazon EC2 instances:
- Networking
- VPC: d-vpc-002-vpc
- Subnets
- d-vpc-002-subnet-private1-us-east-1a
- d-vpc-002-subnet-private2-us-east-1b
- Security group:
Create a new security group- Security group name:
d-sg-saa-ecs-host - Security group description:
Allow All TCP from ALB - Inbound rule: Cho phép ssh từ SG của bastion host
- Security group name:
- Tags: Key:
Name, Value:d-ecs-SAA-{cloudmentor}-cluster01
Hình ảnh minh họa
ec6c2f6a-eedc-4bec-b90d-83a806dba238.png
3c2babc1-d73f-446c-a992-b408f8c150b6.png
ad5a3a6c-e251-48a9-b8e1-db2cdd8f3b72.png
2c449c59-fe08-4802-ad16-ef940a570e65.png5. Create Task definition
Vào Console Elastic Container Service -> Task definitions -> Create new task definition
- Task definition configuration
- Task definition family:
custom-nginx-app
- Task definition family:
- Infrastructure requirements
- Amazon EC2 instances:
Checked - Operating system/Architecture:
Linux/X86_64 - Network mode:
bridge - Task size
- CPU:
0.25 vCPU - Memory:
0.25 GB
- CPU:
- Task role:
- Task execution role:
ecsTaskExcutionRole
- Amazon EC2 instances:
- Container - 1
-
Container details
- Name:
custom-nginx-app - Image URI: Copy URI từ ECR repository
4b24a48d-ef88-46ea-be3e-ea9549519180.png- Các Setting khác để default
Hình ảnh minh họa
- Name:
-
5ec32adb-5458-4bf9-8700-7653a1242926.png
52103ce4-71fd-41ed-a128-4ed1ac714e93.png
eba1a1f3-9d94-42e1-8693-cf5be4a2276f.png
5472c883-8118-4403-b3a4-09fb23000189.png
6. Create Target Group
Vào EC2 Console -> Taget Group -> Nhấn Create taget group
- Specify group details
- Choose a target type:
Instances - Target group name:
d-tg-SAA-web-app - Protocol:
HTTP - Port:
80 - VPC:
d-vpc-002-vpc - Tag: Key:
NameValue:d-tg-SAA-web-app - Các setting khác để như default
- Next
- Choose a target type:
- Register targets:
- NOT assign instance
- Create target group
930fd8d2-9351-41de-827a-ab507c4de448.png
7. Create ALB
7.1 Create SG for ALB
-
Name:
d-sg-SAA-ecs-alb -
Description:
Allow http from internet -
VPC:
d-vpc-002-vpc -
Inbound rules
1/1 dòngHTTP TCP 80 0.0.0.0/0 -
Outbound rules
1/1 dòngAll traffic All All 0.0.0.0/0 -
Tags
1/1 dòngName d-sg-SAA-ecs-alb
7.2 Create Application Load Balancer
Vào EC2 Console -> Load Balancers
- Chọn create Application Load Balancer
- Basic configuration
- Load balancer name:
d-alb-SAA-ecs-web-alb - Scheme:
Internet-facing - IP address type:
IPv4
- Load balancer name:
- Network mapping
- VPC: Chọn
d-vpc-002-vpc - Mappings:
- Check
us-east-1a-> Check...public1... - Check
us-east-1b-> Check...public2...
- Check
- VPC: Chọn
- Security groups:
d-sg-SAA-ecs-alb - Listeners and routing
- Protocol:
HTTP - Port:
80 - Default action: Chọn Taget group
d-tg-SAA-web-server
- Protocol:
230765ac-7648-40e7-9be4-80453a967ea8.png
7.3 Modify SG of EC2 (Docker host)
Theo cơ chế dynamic port mapping khi chúng ta chạy nhiều task port 80 trên 2 EC2 (Docker host). Trước khi đi vào port 80 thì ALB sẽ access đến EC2 1 port được sinh ra tự động, vì chúng ta không thể biết ALB acces đến EC2 port nào nên phải Allow All TCP.
Edit Inbound Rule của SG d-sg-saa-ecs-host
d2422117-d926-4f57-a2e0-e9350bf99eb4.png
46a8f9ac-46dd-4956-bb7d-4dec1392f636.png
8. Create ECS Service
- Vào Console Elastic Container Service -> Clusters -> Chọn
d-ecs-SAA-{yourname}-cluster01 - Tại tab Services -> Create
3999d4f8-2e38-4e8e-badd-0758bff41130.png
- Environment
- Compute options:
Launch type - Launch type:
EC2
- Compute options:
- Deployment configuration
- Application type:
Service - Task definition
- Family:
custom-nginx-app - Revision:
{No}(LATEST)(Chọn version LATEST)
- Family:
- Service name:
custom-nginx-svc - Service type:
Replica - Desired tasks:
3
- Application type:
- Load balancing - optional
- Load balancer type:
Application Load Balancer - Load balancer:
d-alb-SAA-ecs-web-alb - Listener:
Use an existing listener- Listener: 80:HTTP
- Target group:
Use an existing target group- Target group name:
d-tg-SAA-web-app
- Target group name:
- Load balancer type:
- Các setting khác để default
Hình ảnh minh họa
14e6cda0-f392-4643-99b8-06d518bf854c.png
e4c56868-e455-4fdd-9462-e7167f7ac4de.png
c4d07d0b-82db-40df-9b1d-68c494cef0e1.png
Confirm 3 task đã run thành công
7d42a8b1-79e5-4160-b1d7-b55f2234ea2f.png
Kiểm tra Health check của các Task ở Target group
94599f0e-3f8a-436a-8eb6-db5d25f76338.png
Port cũng được sinh ra tự động (đó là lý do mình phải Edit SG của EC2 Allow All TCP từ ALB)
9. Test hoạt động
- Access đến DNS của Application LoadBalancer
a5d167a4-acbe-4e20-b46a-863ac45cce1c.png
64e964bc-9eba-4a85-88a4-a2c2f95336b8.png
Update ECS Service
c6bf17ff-9518-4d0c-9807-f528e64f3ee5.png
Tăng số lượng Task lên 5
48e0ee27-686c-4004-b172-69ddf48fb277.png
Quá trình scale out sẽ diễn ra nhanh chóng
fea2f267-0c92-455c-915e-d449a4319c24.png
10. Setting Route53 and access website (optional)
Để Setting Route53 trỏ domain đến Application load balancer các bạn tham khảo bài viết Configuring ALIAS record on Route 53 of AWS
Challenge
Các bạn sẽ đặt câu hỏi "Vậy làm thế nào để triển khai 1 version mới của ứng dụng?". Mình sẽ hướng dẫn cách làm ngay bây giờ.
- Update file
index.html - Sử dụng các command dc cung cấp ở ECR repository -> View push commands để build và push docker image
Note: sử dụng tag mới cho docker image (tag lúc đầu là 20231225_1, thì lần build này mình sẽ change thành 20231225_2)
cecde1f1-4de7-4765-85e6-dcdae744963d.png
Create new Revision của Task definition, Update Image URI
eec11e4c-7084-4227-995b-0be81d253422.png
6a6e1d01-6771-4b7a-84ac-d9ac033ab8d6.png
d8b1b8d8-d2f1-4136-bd67-429dcb9c1f78.png
Update ECS Service
93513efe-8ae6-424b-af99-1150387628cb.png
ffddee14-63ca-4207-9987-5b7f68e821a4.png
Quá trình Deployment rolling update sẽ diễn ra bằng cách tạo ra task mới và stop task cũ.
f89c6f5f-fedf-4a33-94ef-29586005dcdc.png
ca48cc4b-7003-453c-b831-9271e288cd08.png
Nhật xét
Vậy là chúng ta đã hoàn thành bài lab tạo ECS cluster, build và deploy ứng dụng trên ECS. Mặc dù mọi thứ là thủ công tuy nhiên để cho các bạn dễ hình dung và tiếp cận dễ dàng.
Trong thực tế việc Xây dựng Cluster hay Deploy sẽ triển khai tự động
- Sử dụng IaC để xây dựng và quản lý hạ tầng
- Sử dụng CI/CD cho việc Build và Deploy
Mình sẽ còn viết về chủ đề ECS ở những bài blog sau này!
Clean up
- Delete NAT Gateway
- Terminated Bastion host
- Delete ECS service
- Delete ECS Cluster
- Delete Load balancers
- Delete Target groups
- Delete ECR repo:
d-ecr-saa-nginx-custom - Release Elastic IP addresses
- Delete Role:
SAA-PushImagesToECR-EC2Role - Delete VPC:
d-vpc-002-vpc - Delete Task definition
- Trước tiên cần Deregister tất cả các revision
9e223acc-d89f-47a9-95a6-fc6c1bd8d37a.png
Tiếp tục chọn các revision đã bị Inactive và delete
5b934578-e5d1-4876-9a40-f60727bc241c.png
Bài thực hành khá dài và chắc mọi người cũng mệt rồi, pha cốc cafe + mở một bài nhạc và Relax thôi !!!