Set up CloudWatch alarms and SNS topics in AWS

Table of contents

What is Amazon CloudWatch?

Amazon CloudWatch is an AWS monitoring and observability service that helps track and manage the performance and operational health of AWS resources and applications. It provides real-time data on metrics, logs, and events to ensure applications and services are running efficiently.

Key Features:

  1. Metrics Collection: CloudWatch can monitor metrics from AWS resources (like EC2 instances, RDS databases, and Lambda functions) and custom metrics from applications.

  2. Alarms: You can set up alarms to trigger actions based on thresholds. For example, an alarm can trigger an auto-scaling action or send notifications if CPU usage exceeds a certain limit.

  3. Logs Monitoring: CloudWatch Logs allows you to collect, monitor, and analyze logs from applications and AWS services. Based on log events, you can also set metric filters.

  4. Dashboard: CloudWatch provides customizable dashboards that visually represent metrics, making it easier to understand performance trends at a glance.

  5. Events: CloudWatch Events (now part of Amazon EventBridge) can respond to changes in your AWS environment by triggering actions such as Lambda functions, ECS tasks, or SNS notifications.

  6. Insights: CloudWatch Logs Insights helps query and analyze logs to diagnose issues or identify trends, which is useful for troubleshooting.

Use Cases:

  • Monitoring the health and performance of AWS services and applications.

  • Triggering actions or scaling based on metrics and thresholds.

  • Logging and analyzing application and infrastructure events.

  • Visualizing application performance and trends.

What is Amazon SNS?

Amazon Simple Notification Service (Amazon SNS) is a fully managed messaging service provided by AWS that enables the delivery of messages or notifications to subscribers in a decoupled and scalable manner. It is often used for building distributed applications and notifying users or systems of events or changes.

Key Features:

  1. Topic-Based Pub/Sub: SNS follows the publish-subscribe (pub/sub) messaging model, where a publisher sends messages to a topic, and subscribers receive those messages.

  2. Multiple Delivery Protocols: SNS supports various protocols for message delivery, including:

    • Email and SMS

    • HTTP/HTTPS endpoints

    • AWS Lambda functions

    • Amazon SQS (Simple Queue Service)

  3. Fan-Out Pattern: Messages sent to an SNS topic can be delivered to multiple subscribers simultaneously, enabling the fan-out architecture for event-driven applications.

  4. Message Filtering: SNS allows message filtering based on message attributes, ensuring that subscribers only receive messages they are interested in.

  5. Message Durability: Messages are redundantly stored across multiple availability zones, ensuring durability and high availability.

  6. Serverless Integration: SNS integrates seamlessly with AWS services like Lambda, SQS, CloudWatch, and more, making it easy to build event-driven and serverless applications.

Common Use Cases:

  • Application Notifications: Sending alerts or notifications to users when specific events occur (e.g., a new message or system failure).

  • System-to-System Messaging: Enabling communication between microservices in distributed systems.

  • Event-Driven Architectures: Triggering actions based on changes or events in an application.

  • Fan-Out to SQS: Distributing messages to multiple SQS queues for parallel processing.

Task :

  • Create a CloudWatch alarm that monitors your billing and sends an email to you when it reaches $2.

  • Delete your billing Alarm that you created now.


    Here’s a step-by-step guide on how to create and delete a CloudWatch billing alarm that sends an email when AWS charges exceed $2.

Task 1: Create a CloudWatch Billing Alarm

  1. Log in to AWS Management Console:

  2. Enable Billing Alerts (If Not Already Enabled):

    • Navigate to the Billing Dashboard in the AWS Billing Management Console.

    • Click on Billing Preferences.

    • Check the box for Receive Billing Alerts and save the changes.

  3. Create a Billing Alarm:

    • Go back to the CloudWatch console.

    • Under Alarms, click Create Alarm.

    • In the Create Alarm wizard:

      • Select Metric: Click on Select Metric, then choose Billing -> Total Estimated Charge.

      • Select EstimatedCharges metric and click Select Metric.

    • Conditions:

      • Under the Threshold type, choose Static.

      • Under Whenever EstimatedCharges is..., select Greater/Equal and enter 2.

    • Actions:

      • Select Add Notification.

      • For Send Notification To, create or choose an existing SNS topic.

      • Enter your email address in the subscription field. You will receive a confirmation email, so be sure to confirm it.

    • Name: Enter a name for the alarm, such as BillingAlarm-$2.

    • Click Create Alarm.


Task 2: Delete the Billing Alarm

  1. Go to CloudWatch Dashboard:

    • Navigate to the Alarms section of CloudWatch.
  2. Find the Billing Alarm:

    • Locate the alarm you created (e.g., BillingAlarm-$2).
  3. Delete the Alarm:

    • Select the alarm and click on the Actions dropdown.

    • Choose Delete and confirm the deletion.

AWS Elastic Beanstalk

What is AWS Elastic Beanstalk?

AWS Elastic Beanstalk is a fully managed service that makes it easy to deploy, manage, and scale web applications and services. It abstracts the underlying infrastructure, allowing developers to focus on writing code without worrying about managing servers, networking, or load balancing.


Key Features:

  1. Easy Deployment: You can deploy applications in various programming languages, including Java, Python, Node.js, Ruby, Go, .NET, and PHP, with just a few clicks or using the CLI.

  2. Managed Environment: Elastic Beanstalk automatically handles the provisioning, load balancing, scaling, and monitoring of the infrastructure.

  3. Environment Control: Although managed, it provides flexibility to access and customize resources (e.g., EC2 instances, databases).

  4. Health Monitoring: Elastic Beanstalk offers real-time application health monitoring and integrates with AWS CloudWatch for detailed metrics and alarms.

  5. Application Versioning: Supports versioning of applications, making rollbacks and updates easier.

  6. Auto Scaling: It automatically adjusts the capacity to handle varying levels of traffic, ensuring application availability and performance.

  7. Customization: You can define environment configurations and use extensions (.ebextensions) to further customize your application.


How It Works:

  1. Create an Application: Upload your code (ZIP file or Git repo) to Elastic Beanstalk.

  2. Configure Environment: Choose the environment type (e.g., Web Server Environment) and specify the platform (e.g., Python, Java).

  3. Deployment: Elastic Beanstalk provisions and configures resources like EC2 instances, load balancers, security groups, and databases.

  4. Scaling & Monitoring: The service automatically scales up/down based on traffic and monitors the health of the application.


Use Cases:

  • Web and API applications

  • Microservices

  • Continuous integration/continuous delivery (CI/CD) pipelines

  • Test and development environments


Benefits:

  • Simplified Deployment: Quickly deploy without managing underlying infrastructure.

  • Flexibility: Full control over AWS resources if needed.

  • Scalability: Automatically adjusts to traffic fluctuations.

  • Cost Efficiency: Pay only for the underlying AWS resources Elastic Beanstalk provisions.

Why do we need AWS Elastic Beanstalk?

AWS Elastic Beanstalk is valuable because it simplifies the deployment and management of web applications and services without requiring developers to manage the underlying infrastructure. Here’s why it’s useful:


1. Simplified Deployment & Management

Elastic Beanstalk takes care of provisioning, configuring, monitoring, and scaling the infrastructure for your application. This allows developers to focus on writing code instead of dealing with complex infrastructure tasks like load balancing, instance management, and networking.


2. Automatic Scaling

Elastic Beanstalk can automatically scale up or down based on traffic to ensure your application performs well under varying load conditions. It ensures high availability without manual intervention.


3. Flexibility and Customization

While Elastic Beanstalk manages the environment, it still allows you to customize resources (e.g., modify EC2 instances, load balancers, or security settings). This flexibility makes it ideal for those who need managed services with some control over configurations.


4. Rapid Development and Deployment

You can quickly deploy web applications by uploading your code, choosing a platform, and letting Elastic Beanstalk handle the rest. This speeds up development and enables frequent deployments without worrying about infrastructure management.


5. Multi-Language Support

Elastic Beanstalk supports multiple platforms and programming languages, including Python, Java, .NET, Ruby, Node.js, Go, and PHP. This makes it adaptable for various types of applications and development teams.


6. Built-in Monitoring and Health Checks

Elastic Beanstalk integrates with AWS CloudWatch to provide monitoring, application metrics, and alarms. It also includes real-time health monitoring to help detect and resolve application performance issues quickly.


7. Cost Efficiency

You only pay for the AWS resources Elastic Beanstalk provisions, such as EC2 instances and load balancers. The service itself has no additional cost, making it a cost-effective option for application deployment.


8. Version Control and Rollbacks

Elastic Beanstalk supports application versioning, making it easy to roll back to a previous version if an issue arises after deployment.


9. Integrated CI/CD Support

Elastic Beanstalk integrates with AWS CodePipeline and other CI/CD tools, streamlining continuous integration and deployment workflows for faster, automated deployments.

Advantages of AWS Elastic Beanstalk:

  1. Simplified Deployment and Management

    • Elastic Beanstalk automates the deployment of applications, including provisioning resources, load balancing, scaling, and monitoring. Developers can focus solely on writing code without worrying about the underlying infrastructure.
  2. Auto-Scaling

    • It automatically scales applications up or down based on demand, ensuring optimal performance during peak traffic and cost savings during low traffic.
  3. Multi-Language and Platform Support

    • Elastic Beanstalk supports a wide range of programming languages and platforms such as Java, Python, Node.js, .NET, Ruby, Go, and PHP, making it versatile for various applications.
  4. Customization and Full Control

    • Although managed by AWS, Elastic Beanstalk allows full access to resources (e.g., EC2 instances, load balancers, and security groups) for fine-tuning or making custom configurations.
  5. Built-in Monitoring and Health Checks

    • Elastic Beanstalk integrates with AWS CloudWatch to provide real-time application monitoring, metrics, logs, and health status to help detect and resolve issues quickly.
  6. Rapid Deployment

    • With Elastic Beanstalk, deploying applications is as simple as uploading your code. The service takes care of setting up the environment, and speeding up the development lifecycle.
  7. Application Version Control

    • Elastic Beanstalk supports versioning, enabling you to deploy and manage multiple versions of your application, roll back to a previous version, or test different versions easily.
  8. Environment Isolation

    • You can create separate environments for development, testing, staging, and production, ensuring isolation for safe testing and better application lifecycle management.
  9. CI/CD Integration

    • Elastic Beanstalk integrates seamlessly with AWS CodePipeline, Git, and other CI/CD tools, making it easier to automate builds and deployments.
  10. Zero Additional Cost

    • Elastic Beanstalk is free to use—you only pay for the underlying AWS resources (e.g., EC2 instances, S3, RDS) used by your application, making it cost-effective.
  11. Security and Compliance

    • Elastic Beanstalk leverages AWS’s robust security features, including IAM roles, VPC integration, and encryption, to help secure applications and maintain compliance.
  12. Environment Cloning and Blue/Green Deployments

    • You can clone environments and use blue/green deployments to test new versions in parallel or roll back with minimal downtime if issues are detected.

Components of AWS Elastic Beanstalk:

AWS Elastic Beanstalk is composed of several core components that work together to deploy, manage, and scale applications. Here’s a breakdown of its key components:


1. Application

  • The logical container for your Elastic Beanstalk setup, representing your web application as a whole.

  • It consists of one or more versions and environments.

  • You can manage multiple applications from the Elastic Beanstalk console.


2. Application Version

  • A deployable version of your application, typically stored as a ZIP file containing the code and configuration.

  • Elastic Beanstalk allows you to deploy different versions and provides the ability to roll back to a previous version if needed.


3. Environment

  • An isolated set of AWS resources running a specific version of your application.

  • Each environment can be configured independently and typically corresponds to stages like development, testing, or production.

  • Environments can have unique configurations such as different instance types or scaling settings.


4. Environment Tier

Elastic Beanstalk provides two environment tiers:

  1. Web Server Environment: Designed to handle HTTP/HTTPS requests and serve dynamic web pages.

  2. Worker Environment: Used for background processing of tasks, typically pulling from Amazon SQS (Simple Queue Service).


5. Environment Configuration

  • A collection of settings and parameters that define how your environment operates (e.g., instance type, scaling rules, security groups).

  • These settings can be adjusted via the Elastic Beanstalk console or configuration files (.ebextensions).


6. Elastic Beanstalk Environment Components

When an environment is created, Elastic Beanstalk provisions and manages the following AWS resources:

  1. Amazon EC2 Instances: Hosts your application.

  2. Auto Scaling Group: Automatically scales the environment based on traffic or defined rules.

  3. Elastic Load Balancer (ELB): Distributes incoming traffic across multiple EC2 instances for high availability.

  4. Amazon S3 Bucket: Stores application versions and logs.

  5. Amazon RDS (Optional): For relational database needs, if enabled.

  6. Amazon CloudWatch: Monitors and provides application and environment metrics and logs.

  7. Amazon SQS (Optional): Used for worker environments to process tasks.


7. Health Monitoring

  • Elastic Beanstalk continuously monitors the health of your application and environment using predefined or custom health checks.

  • Health statuses are displayed in the console (e.g., Green, Yellow, or Red) to help diagnose issues quickly.


8. Configuration Files (.ebextensions)

  • YAML or JSON files are stored in your application’s source bundle.

  • They allow you to customize and extend the environment configuration, such as installing software packages or setting environment variables.


9. Deployment Policies

Elastic Beanstalk supports various deployment strategies:

  1. All at Once: Deploys all instances simultaneously.

  2. Rolling: Deploys in batches to reduce downtime.

  3. Rolling with Additional Batch: Adds a new batch during deployment, ensuring no reduction in capacity.

  4. Immutable: Creates a new environment and switches traffic to it after the deployment.

  5. Blue/Green: Uses a separate environment for new changes, allowing traffic to be switched after successful testing.


10. Logs

  • Elastic Beanstalk collects application logs and environment logs, which can be viewed in the console or exported to Amazon S3 or CloudWatch for further analysis.

Elastic Beanstalk Environment:

An Elastic Beanstalk environment is a set of AWS resources provisioned to run a specific version of an application. It is the core unit where Elastic Beanstalk deploys and manages web applications or services. Each environment is isolated and operates independently, making it ideal for development, testing, staging, and production deployments.


Key Components of an Elastic Beanstalk Environment

  1. Amazon EC2 Instances

    • Virtual machines that host and run your application.

    • You can specify the instance type and size (e.g., t2.micro, m5.large).

  2. Elastic Load Balancer (ELB)

    • Distributes incoming traffic across multiple EC2 instances to ensure high availability and fault tolerance.
  3. Auto Scaling Group

    • Automatically adjusts the number of running EC2 instances based on traffic or predefined scaling policies.
  4. Amazon S3 Bucket

    • Stores application versions, deployment artifacts, and environment logs.
  5. Amazon RDS (Optional)

    • Provides relational databases if the environment requires persistent data storage.
  6. Amazon CloudWatch

    • Monitors environment metrics (e.g., CPU usage, memory utilization, and application health) and triggers alarms based on thresholds.
  7. Amazon SQS (Optional for Worker Environments)

    • Used in worker environments to manage task queues for background job processing.

Environment Tiers

Elastic Beanstalk offers two main environment tiers:

  1. Web Server Environment

    • Designed for applications that handle HTTP/HTTPS requests.

    • Commonly used for web applications, REST APIs, and dynamic websites.

    • Includes an Elastic Load Balancer, Auto Scaling Group, and EC2 instances to manage traffic and scale.

  2. Worker Environment

    • Processes background tasks or jobs that are not time-sensitive.

    • Uses Amazon SQS to queue tasks and automatically manages the number of worker instances based on the queue’s size.


Environment Lifecycle

  1. Create Environment: You can create a new environment by uploading your application code and choosing a platform (e.g., Python, Node.js).

  2. Deploy Application: Elastic Beanstalk automatically deploys your application to the environment.

  3. Monitor Environment: Elastic Beanstalk continuously monitors the health of the environment (e.g., Green for healthy, Yellow for warnings, and Red for errors).

  4. Scale Environment: Auto Scaling can increase or decrease the number of EC2 instances based on traffic or metrics.

  5. Terminate Environment: You can delete the environment, which shuts down all associated AWS resources.


Environment Configuration Options

  • Instance Type: Define the size and type of EC2 instances used.

  • Load Balancer Settings: Customize the load balancer for different traffic patterns.

  • Scaling Policies: Set up thresholds to control auto-scaling behavior.

  • Environment Variables: Define variables to be used by the application at runtime.

  • Health Checks: Configure health monitoring to detect and respond to failures.


Deployment Policies

Elastic Beanstalk supports various deployment methods for environments:

  • All at Once: Deploy all instances simultaneously.

  • Rolling: Deploy instances in batches to reduce downtime.

  • Rolling with Additional Batch: Ensures full capacity is maintained during deployment.

  • Immutable: Creates a new environment for the updated version and switches traffic after successful deployment.

  • Blue/Green: Deploys to a new environment, and after testing, switches traffic from the old environment.


Benefits of Elastic Beanstalk Environments

  • Isolation: Each environment is independent, reducing the risk of errors in one environment affecting others.

  • Scalability: Automatically adjusts resources based on traffic.

  • Customizability: Full control over environment configurations if needed.

  • Simplified Monitoring: Health status and logs help with troubleshooting.

  • Ease of Rollback: Supports multiple application versions for quick rollbacks.

Deploy the 2048 game using the AWS Elastic Beanstalk:

To deploy the 2048 game using AWS Elastic Beanstalk, follow these steps:


1. Clone the 2048 Game Repository

First, clone the GitHub repository to your local machine.

git clone https://github.com/Simbaa815/2048-game.git
cd 2048-game

2. Ensure the Correct Application Structure

AWS Elastic Beanstalk expects a specific application structure. Since this is a static website, ensure the files (e.g., index.html, JavaScript, and CSS) are present in the root directory.


3. Initialize Elastic Beanstalk (Using AWS CLI)

Ensure that you have the AWS CLI and Elastic Beanstalk CLI (EB CLI) installed and configured.

Log in to your AWS account:

aws configure

Initialize the Elastic Beanstalk application:

eb init
  • Choose the region where you want to deploy.

  • Select the platform as "Node.js" or "Static Files" (depending on the game's structure).

  • Confirm settings.


4. Create and Deploy the Environment

Create an environment and deploy the application:

eb create 2048-game-env

This will:

  • Provision a new environment with the required AWS resources (e.g., EC2, S3).

  • Deploy the application to the environment.

Monitor the deployment progress through the terminal.


5. Access the Deployed Application

Once the environment is successfully deployed, you will receive a URL similar to:

http://2048-game-env.YourRegion.elasticbeanstalk.com

Visit the URL to confirm that the 2048 game is accessible.


7. Updating the Application

If you make changes to the game, redeploy the updated code:

git add .
git commit -m "Updated game files"
eb deploy

8. Deleting the Environment (If No Longer Needed)

To delete the environment and associated resources:

eb terminate 2048-game-env

ECS

What is ECS?

Amazon ECS (Elastic Container Service) is a fully managed container orchestration service provided by AWS. It enables you to run, manage, and scale containerized applications using Docker containers without the need to manage the underlying infrastructure.


Key Features of ECS

  1. Container Orchestration

    • ECS schedules and deploys containers across EC2 instances or AWS Fargate, ensuring efficient resource utilization and scalability.
  2. AWS Fargate Integration

    • ECS is deeply integrated with AWS Fargate, a serverless compute engine that allows you to run containers without managing EC2 instances. You only define the resources needed for each container, and Fargate handles the rest.
  3. Task Definition

    • ECS uses a Task Definition, a JSON configuration file that specifies details about your containers, such as:

      • Docker image to use.

      • Memory and CPU requirements.

      • Network and logging configurations.

  4. Service Management

    • ECS Services manage and maintain the desired number of running tasks (containers). If a task stops, ECS automatically restarts it to ensure high availability.
  5. Load Balancing

    • ECS integrates with Elastic Load Balancing (ELB) to distribute incoming traffic across running containers.
  6. Auto Scaling

    • ECS can automatically scale the number of containers based on traffic or custom metrics (e.g., CPU and memory usage).
  7. Networking and Security

    • ECS integrates with AWS VPC, Security Groups, and IAM roles, ensuring network isolation and secure access control.
  8. Monitoring and Logging

    • ECS provides integration with Amazon CloudWatch to collect logs, monitor metrics, and set up alarms for performance and health monitoring.
  9. Cluster Management

    • ECS organizes containers into clusters (logical groupings of resources) to manage applications across multiple instances or serverless environments.

ECS Launch Types

  1. Fargate Launch Type

    • Serverless option where AWS handles infrastructure management.

    • Ideal for reducing operational overhead and focusing on application logic.

  2. EC2 Launch Type

    • Containers are deployed on a cluster of EC2 instances.

    • Allows for more granular control over instances and resource allocation.


Use Cases for Amazon ECS

  1. Microservices Architecture

    • ECS helps deploy and manage microservices, ensuring each service is isolated and independently scalable.
  2. Batch Processing

    • Run batch jobs in containers with automatic scaling and scheduling.
  3. Web Applications

    • Deploy scalable, fault-tolerant web applications with load balancing and automated recovery.
  4. CI/CD Pipelines

    • Integrate ECS with AWS CodePipeline and CodeDeploy for automated build, test, and deployment workflows.

Benefits of Amazon ECS

  1. Fully Managed Service

    • AWS handles container orchestration, health checks, and scaling.
  2. Seamless Integration with AWS Ecosystem

    • ECS integrates natively with services like IAM, CloudWatch, VPC, RDS, and ELB for better application management.
  3. Flexible Deployment Options

    • Choose between Fargate for serverless computing or EC2 for full control over the infrastructure.
  4. High Availability

    • ECS ensures that applications are resilient with automated restarts, scaling, and load balancing.
  5. Cost Optimization

    • Pay only for the resources used, and leverage Fargate to eliminate unnecessary infrastructure costs.

Difference between EKS and ECS?

FeatureEKS (Elastic Kubernetes Service)ECS (Elastic Container Service)
Orchestration TechnologyKubernetes (open-source)AWS native (custom engine)
ComplexityHigh (Kubernetes learning curve)Low (AWS-specific, easier to set up)
Use CaseLarge-scale, cross-cloud, hybrid, multi-cluster setupsSimple, AWS-centric microservices, serverless options
FlexibilityHighly flexible, multi-cloud, open ecosystemAWS-centric, simpler, less flexible
ScalingAdvanced scaling (manual configuration required)Simple auto-scaling with AWS integration
Service IntegrationKubernetes ecosystem + AWS servicesAWS services, simpler integration
CostControl plane cost + resources (more expensive for large)Free for ECS + cost of resources (usually cheaper)
Community & SupportLarge Kubernetes community, cross-cloud supportAWS-specific, smaller community

Task :

Set up ECS (Elastic Container Service) by setting up Nginx on ECS.


To set up NGINX on Amazon ECS (Elastic Container Service), follow these steps:

Prerequisites:

  1. AWS Account: You must have an AWS account to create ECS clusters and resources.

  2. AWS CLI & ECS CLI: Install AWS CLI and ECS CLI if you haven't already.


Step 1: Create an ECS Cluster

First, let's create an ECS cluster where we will deploy NGINX.

  1. Using AWS Console:

    • Navigate to the ECS Console: ECS Dashboard.

    • Click Create Cluster.

    • Select Networking only (Fargate).

    • Give the cluster a name, e.g., nginx-cluster.

    • Click Create.

  2. Using ECS CLI:

    • First, configure the ECS CLI with the necessary AWS credentials:

        ecs-cli configure --region <aws-region> --access-key <aws-access-key> --secret-key <aws-secret-key> --cluster nginx-cluster
      
    • Create the ECS cluster:

        ecs-cli up --cluster nginx-cluster --capability-iam --size <instance-type> --instance-count 1 --region <aws-region>
      

Step 2: Create a Task Definition for NGINX

  1. Create Dockerfile for NGINX:
    You will need to create a task definition for NGINX. Here's a simple approach:

    • Create a Dockerfile (if you want to customize it):

        FROM nginx:latest
        COPY ./html /usr/share/nginx/html
      

      This will copy custom HTML files into the NGINX container. However, if you just want to use the default NGINX setup, you can skip this step and use the official NGINX Docker image directly.

  2. Create ECS Task Definition:

    • Go to the ECS Console, and click on Task Definitions > Create new Task Definition.

    • Select the launch type as Fargate.

    • Name your task (e.g., nginx-task).

    • Under Container Definitions, click Add Container and use the official NGINX Docker image: nginx:latest.

      • Set a container name (e.g., nginx-container).

      • Set the memory (e.g., 512MB) and CPU (e.g., 0.25 vCPU).

      • Set the port mappings:

        • Container port: 80

        • Host port: 80

    • Click Create after entering all details.


Step 3: Create a Service for NGINX

  1. Using the ECS Console:

    • Navigate to ECS > Clusters > Select your cluster (e.g., nginx-cluster).

    • Click on Create under the Services tab.

    • Select Fargate as the launch type.

    • Choose the Task Definition you just created (e.g., nginx-task).

    • Set the service name (e.g., nginx-service).

    • Set desired tasks (e.g., 1).

    • Set Deployment type as Rolling update.

    • Under Load Balancing, choose whether to use an existing Application Load Balancer (ALB) or Create a new one.

    • Review the settings and click Create Service.

  2. Using ECS CLI:

    • Run the following command to create a service:

        ecs-cli compose --file <path-to-docker-compose-file> --project-name nginx-service up
      
    • Ensure you specify the docker-compose.yml file that defines NGINX containers and configurations.


Step 4: Create a Load Balancer (Optional)

If you want your NGINX container to be accessible via HTTP, it’s a good practice to use an Application Load Balancer (ALB).

  1. Go to the EC2 Console and navigate to Load Balancers > Create Load Balancer.

  2. Select Application Load Balancer.

  3. Choose the VPC and subnets.

  4. Set up listeners (use HTTP on port 80).

  5. Once the ALB is created, attach it to your ECS service:

    • Go back to your ECS service and modify the service to associate it with the ALB.

Step 5: Verify Deployment

  1. Find the Public IP of the ECS service.

    • If using Fargate, you can find the public IP of the task by navigating to the ECS Console > Task > ENI (Elastic Network Interface).
  2. Open the Public IP or the ALB URL in a browser to verify that NGINX is running.


Step 6: Clean Up

After completing the setup, you can terminate the ECS service and cluster when done.

  1. Delete ECS Service:

     ecs-cli compose --project-name nginx-service down
    
  2. Delete the ECS Cluster:

     ecs-cli down --region <aws-region> --force
    

Additional Notes:

  • ECS with Fargate: Using AWS Fargate allows you to run containers without managing EC2 instances, making it a great choice for simplified deployment.

  • Security: Ensure your ECS task has the right security groups and IAM roles assigned for network access and permissions.

This guide walks you through setting up NGINX on ECS, but you can adjust the configurations for more complex deployments or scaling needs. Let me know if you need more details or further assistance!