Aws Service Can Be Used To Run Docker Containers

Aws Service Can Be Used To Run Docker Containers

Reading time1 min
#Cloud#DevOps#Containers#AWSFargate#Docker#ECS

AWS Fargate: Containerized Deployments Without Server Management

Containerized workloads demand agility, but managing a cluster of EC2 nodes—even with automation—introduces operational drag. Routine patching, instance lifecycle events, network drift: all possible vectors for downtime or misconfiguration. Fargate, as a serverless compute engine for ECS and EKS, closes that operational gap.

Scenario: You have a stateless Node.js web service, already dockerized, and the requirement is to deploy it securely at scale—without touching a single server or cluster node. Here’s a direct, tested path using AWS Fargate with ECS. No EC2 instances. No OS patching.


AWS Fargate: Key Properties

  • No Underlying Host to Manage: Fargate allocates and manages infrastructure; you specify vCPU/memory at the task level.
  • Kernel Isolation: Workloads are isolated at the VM level—no kernel or filesystem sharing between tenants.
  • Elastic Compute: Scaling is determined by ECS service configuration and Fargate’s backend. Zero cold start if you pre-warm services.
  • Integrated IAM and Networking: Each task can assume IAM roles; ENIs per task mean fine-grained VPC controls.
  • Billing Granularity: Per-second billing based on CPUs and RAM (minimum one minute).
  • Native Logging & Monitoring: CloudWatch integration is default, but structured log configs are your responsibility.

Deployment Walkthrough: Node.js Container to Fargate

Below: rapid, stepwise approach with actual command lines, version references, and practical caveats.


1. Building the Container Image

Reference application (Node.js 14-alpine). Simple HTTP container, explicit EXPOSE for ECS network mappings.

// app.js
const http = require('http');
const PORT = 3000;
http.createServer((req, res) => res.end('Hello from AWS Fargate!')).listen(PORT);

Dockerfile:

FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]

Local build:

docker build --platform linux/amd64 -t my-node-app:latest .

Note: If building on Apple Silicon, use --platform linux/amd64 to avoid runtime error on AWS Fargate’s x86_64 backend.


2. Push to Amazon ECR

Fargate requires a container registry in VPC scope (i.e., ECR).

aws ecr create-repository --repository-name my-node-app --region us-east-1
REPO_URI=123456789012.dkr.ecr.us-east-1.amazonaws.com/my-node-app

aws ecr get-login-password --region us-east-1 \
  | docker login --username AWS --password-stdin $REPO_URI

docker tag my-node-app:latest $REPO_URI:latest
docker push $REPO_URI:latest

Gotcha: Ensure repository policy allows the ECS Task Role to pull images, especially with cross-account ECS deployments.


3. ECS Cluster Preparation

Launch an ECS cluster with only networking resources (no EC2 capacity).

  • Go to ECS > Clusters > Create cluster > Networking only (Fargate).
  • Name: my-fargate-cluster.

No compute layer—all tasks run managed.


4. Task Definition (Fargate Compatibility)

Sample JSON fragment for an ECS Task Definition (fargate-task.json):

{
  "family": "my-node-app-task",
  "networkMode": "awsvpc",
  "cpu": "256",
  "memory": "512",
  "requiresCompatibilities": ["FARGATE"],
  "containerDefinitions": [
    {
      "name": "my-node-app",
      "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-node-app:latest",
      "portMappings": [{"containerPort": 3000, "protocol": "tcp"}],
      "essential": true
    }
  ]
}

Register:

aws ecs register-task-definition --cli-input-json file://fargate-task.json

Assign IAM roles for secrets or AWS API access if required via taskRoleArn.


5. Running the Container Task

Quick launch (public subnet with auto-assigned IP):

aws ecs run-task \
  --cluster my-fargate-cluster \
  --launch-type FARGATE \
  --task-definition my-node-app-task \
  --network-configuration "awsvpcConfiguration={subnets=[subnet-abc123],securityGroups=[sg-012345],assignPublicIp=ENABLED}"

Security: Fine-tune the security group: restrict ingress to port 3000 or route through an Application Load Balancer for production. Fargate tasks without a public IP require an internal load balancer.


6. Load Balancer Integration (Optional but Production-Grade)

For a public endpoint with stable DNS, use an Application Load Balancer. Route traffic:

  • Target group: Protocol TCP/HTTP, port 3000.
  • Listener: HTTP port 80/443 (ALB).
  • Attach ECS Service to target group.

Network diagram:

[User] -> [ALB:80/443] -> [Fargate Task ENI in VPC:3000]

Known Issue: ALB health checks default to path /. Your app must respond on / or health checks will fail. Consider explicit healthcheck paths in both task and ALB settings.


Reflection: Why Bother With Fargate?

Serverless containers provide a crisp separation: focus on application logic, let AWS manage the computability surface. No capacity reservations, no node scaling scripts, no custom AMIs.

A trade-off: cold start latency is nonzero when scaling from zero; e.g., expect 30–60s on initial scale-out. For latency-sensitive APIs, keep a minimum task count of 1.


Non-obvious Implementation Tip

To persist logs, configure awslogs or firelens as a sidecar in your ECS Task Definition. Native STDOUT is not persisted unless explicitly routed.

Sample sidecar snippet:

{
  "name": "logrouter",
  "image": "amazon/aws-for-fluent-bit:2.25.1",
  "essential": true,
  "firelensConfiguration": {"type": "fluentbit"},
  // ...
}

Also, to attach persistent storage, specify EFS volumes in your task definition—useful for legacy apps with stateful file access.


Summary

AWS Fargate eliminates infrastructure management overhead for container workloads. Build locally, push to ECR, define tasks, and run at scale—all without a single server under your control. For environments favoring least-ops and fast iteration, Fargate is often the correct tradeoff.

If you hit issues like RESOURCE:ENI provisioning failures or cryptic CannotPullContainerError, check subnet route tables, NAT gateways, and task role permissions. Fargate’s abstraction is powerful—but troubleshooting inevitably requires a clear understanding of AWS networking and IAM.


Questions about IAM permissions on Fargate tasks? Ran into throttling on ECR pulls at scale? Add your notes below.