Deploy a Golang application on ECS Fargate
Build an ECS Fargate cluster and launch a simple Go application Docker container on top of it. Here are the steps for launching the Terraform code and the Go application.
Environment
- VPC
- Two public subnets.
- One ECS cluster.
- ALB
Instructions for launching the Go application
Create a repository in ECR
Build and push the Docker image to the ECR repository
Create a Docker image of the actual Go application to run. Use the following commands to build the Docker image and push it to the ECR repository.
cd fargate-go-example/docker/docker-image
aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin <Your AWS account number>.dkr.ecr.<Your region>.amazonaws.com
docker build -t go-example .
docker tag go-example:latest <Your AWS account number>.dkr.ecr.<Your region>.amazonaws.com/go-example:latest
docker push <Your AWS account number>..dkr.ecr.<Your region>.amazonaws.com/go-example:latest
ECS Operations.
ECS CLI Installation.
Install the CLI to operate the ECS on your PC. See the AWS documentation for instructions on how to install and initially configure it.
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_CLI_installation.html
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_CLI_Configuration.html
Update the image name of docker-compose.yml as a base for ECS task definitions.
We will use docker-compose.yml as an input to the ecs-cli compose command that we will run later.
Change the
cd fargate-go-example/docker
vim docker-compose.yml
version: '3'
services:
fargate-go-example:
image: ' <AWS account number>.dkr.ecr.ap-northeast-1.amazonaws.com/go-example:latest'
ports:
- '8080:8080'
Modification of ecs-params.yml as a base for ECS task definition
Use ecs-params.yml as an input to the ecs-cli compose command to be run later.
Replace the following values of subnets and security_groups with the IDs of the ones you created with Terraform.
version: 1
task_definition:
task_execution_role: ecsTaskExecutionRole
ecs_network_mode: awsvpc
task_size:
mem_limit: 0.5GB
cpu_limit: 256
run_params:
network_configuration:
awsvpc_configuration:
subnets:
- "subnet-0d9ee166fc862a5df"
- "subnet-02821c5131011d174"
security_groups:
- "sg-08c2299a6c28415f8"
assign_public_ip: ENABLED
Deploy ECS Service
Start the ECS service. Execute the following command. Enter the ARN of the target group created by erraform in –target-group-arn.
timeout 30m ecs-cli compose \
--file docker-compose.yml \
--ecs-params ecs-params.yml \
--project-name fargate-go-example\
--cluster fargate-go-example \
service up --launch-type FARGATE \
--container-name fargate-go-example \
--container-port 8080 \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:xxxxxxxxxxxxx:targetgroup/fargate-go-example/xxxxxxxxxxxxxxx \
--region ap-northeast-1 \
--timeout 30