0
0
AwsHow-ToBeginner · 4 min read

How to Deploy a Container on AWS ECS Quickly and Easily

To deploy a container on AWS ECS, first create a task definition that describes your container. Then, create an ECS cluster and run a service using that task definition to launch and manage your container instances.
📐

Syntax

Deploying a container on ECS involves these main parts:

  • Task Definition: A JSON file that defines your container image, CPU, memory, and ports.
  • Cluster: A logical group of container instances where your tasks run.
  • Service: Manages running and scaling your tasks on the cluster.
json
{
  "family": "my-task",
  "containerDefinitions": [
    {
      "name": "my-container",
      "image": "nginx:latest",
      "cpu": 256,
      "memory": 512,
      "essential": true,
      "portMappings": [
        {
          "containerPort": 80,
          "hostPort": 80
        }
      ]
    }
  ]
}
💻

Example

This example shows how to deploy an NGINX container on ECS using AWS CLI commands.

bash
aws ecs create-cluster --cluster-name my-cluster

aws ecs register-task-definition \
  --family my-task \
  --container-definitions '[{"name":"my-container","image":"nginx:latest","cpu":256,"memory":512,"essential":true,"portMappings":[{"containerPort":80,"hostPort":80}]}]'

aws ecs create-service \
  --cluster my-cluster \
  --service-name my-service \
  --task-definition my-task \
  --desired-count 1 \
  --launch-type EC2
Output
Cluster created: my-cluster Task definition registered: my-task Service created: my-service
⚠️

Common Pitfalls

Common mistakes when deploying containers on ECS include:

  • Not specifying the correct containerPort and hostPort in the task definition, causing port conflicts.
  • Forgetting to create or use an ECS cluster before creating a service.
  • Using incompatible launch types (e.g., trying to run EC2 tasks without EC2 instances in the cluster).
  • Not setting the essential flag to true for the main container, which can cause the task to stop unexpectedly.
json
Wrong task definition snippet:
{
  "containerPort": 80,
  "hostPort": 0
}

Right task definition snippet:
{
  "containerPort": 80,
  "hostPort": 80
}
📊

Quick Reference

Remember these quick tips:

  • Always register a task definition before creating a service.
  • Use aws ecs create-cluster to make a cluster.
  • Use aws ecs create-service to run your container.
  • Check your container ports and memory settings carefully.

Key Takeaways

Create a task definition describing your container image and resources.
Set up an ECS cluster to host your container tasks.
Use an ECS service to run and manage your container instances.
Ensure port mappings and essential flags are correctly configured.
Use AWS CLI commands or the AWS Console to deploy your container easily.