Deploy a Docker container on Fargate through Serverless Framework
Amazon Elastic Container Service or (ECS) is a fully managed container orchestration service that allows you to host containers in AWS cloud. Fargate is a technology that manages the ECS clusters and scales according to load.
Creating the Docker file
Dockerfile
is a file that is responsible for all the configuration of the container image. Below is a sample Dockerfile
for running a node JS application.
FROM node:16
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD [ "npm", "start" ]
For locally running on Mac Silicon Chips, use ` — platform=linux/amd64` tag either in FROM or while runing docker.
ECR repository
ECR stands for Elastic Container Repository, it is a repository service from AWS that allows it to upload container images.
ECR:
Type: AWS::ECR::Repository
Properties:
RepositoryName: repository-name
ECS task
ECS or Elastic Container Service task definition specifies the image to use with each container in the task and CPU and memory to allocate.
TaskDefintion:
Type: AWS::ECS::TaskDefinition
Properties:
ExecutionRoleArn:
Fn::GetAtt:
- TaskExecutionRole
- Arn
ContainerDefinitions:
-
Name: task-defintion-name
Image: ECR repository URI
logConfiguration:
logDriver: awslogs
options:
awslogs-group: group name
awslogs-region: region
awslogs-create-group: true
Cpu: 256
Memory: 512
Essential: true
Cpu: 256
Memory: 512
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
TaskRoleArn:
Fn::GetAtt:
- TaskExecutionRole
- Arn
Adding Fargate as required compatibility is responsible for scaling and maintaining the underlying infrastructure for running ECS task
ECS cluster
ECS cluster is responsible for handling the ECS tasks.
VCUserReportsCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: cluster-name
CapacityProviders:
- FARGATE
DefaultCapacityProviderStrategy:
- CapacityProvider: FARGATE
Weight: 1
Create lambda to trigger ECS task and to set env variables
Finally write a lambda to trigger an ECS task and pass on any env variables required to run the container. The lambda can be configured to run as cron or on http invocation. The Lambda is also responsible for passing the role. The IAM role for lambda can have the iam:passrole
action which allows it pass the role on to the container task on trigger.