[AWS] Hosting Web Application on AWS ECS using Nginx and Load Balancer

Deploying web applications on AWS ECS (Elastic Container Service) with a Load Balancer is a powerful way to achieve high availability and scalability for your web projects. In this tutorial, we’ll go step-by-step through the process of containerizing an application with Nginx, pushing it to Amazon ECR (Elastic Container Registry), and deploying it using AWS ECS with a Load Balancer.

Step 1: Setting Up Your Web Application

To get started, we need a simple web application. Let’s create a straightforward HTML file named index.html to serve as the content for our Nginx server. Here’s a basic example:

This HTML file will be displayed as a “Hello World” page once the deployment is complete.

Step 2: Dockerize the Application

To host this application on ECS, we need to containerize it using Docker. First, create a Dockerfile in your project’s root directory with the following content:

This Dockerfile copies index.html into the default web directory of an Nginx container.

Build and Test the Docker Image Locally

Now, let’s build and test the Docker image locally before pushing it to AWS:

Test locally

Visit http://localhost:8080 in your browser to see if your “Hello, World” page is served correctly.

Step 3: Push the Docker Image to Amazon ECR

With your Docker image tested and ready, the next step is to push it to Amazon ECR. Start by creating a repository in ECR through the AWS Console, and follow these commands to log in and push your image:

At the top of the repository page, you’ll see the View push commands button. Click it to see the steps to push your Docker image to ECR.

Go to the command line and run these commands:

Step 4: Create an ECS Cluster and Task Definition

Navigate to the ECS section in the AWS Console and create a new cluster. Choose the appropriate settings (such as Fargate or EC2 launch type) based on your requirements.

After creating the cluster, define a new ECS Task Definition. Specify the container details such as container name, image URI from ECR, memory limits, and port mappings (e.g., 80 for Nginx). This task definition will be the blueprint ECS uses to deploy and run the container.

Next up we need to create the task definition.

Add a container:

Next, let’s create a service within that Cluster