> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Setup service on ECS for login application

> Deploying a Flask login app to AWS ECS using an Application Load Balancer, creating task definitions and services, validating health, and fixing redirect and networking issues.

Now that the container image is built and pushed to Amazon ECR, deploy the login application as a service on Amazon ECS. This guide walks through creating a task definition, configuring a service with an Application Load Balancer (ALB), validating the deployment, and fixing a common redirect issue in the Flask app.

## Prerequisites

* Image pushed to ECR (copy its image URI).
* An ECS cluster (here, a production cluster).
* Appropriate VPC, subnets, and security groups configured for the ALB and ECS tasks.
* Port 5000 used by the Flask application.

## 1. Create the Task Definition

1. Open the AWS Console and navigate to **ECS**.
2. Click **Task Definitions → Create new task definition**.
3. Give the task definition a descriptive name.
4. Scroll down to add a container:
   * Paste the image URI you copied from ECR into the container image field.
   * Add a port mapping: container port `5000`.
   * Leave other settings at their defaults unless you need resource limits or environment variables.
5. Click **Create**.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/1ccKtG7aZllQmXlF/images/Hands-On-AWS-Project-Deploy-Your-First-Crypto-App/Monolith-to-Microservice-design/Setup-service-on-ECS-for-login-application/amazon-ecs-dashboard-productioncluster-details.jpg?fit=max&auto=format&n=1ccKtG7aZllQmXlF&q=85&s=8e0c7373f39cf5d897af139535dbfb04" alt="The image shows the Amazon Elastic Container Service (ECS) dashboard with a cluster named &#x22;ProductionCluster,&#x22; displaying details like one running service and no pending tasks. A green notification bar indicates a successful task definition creation for &#x22;login-app-microservice:1.&#x22;" width="1920" height="1080" data-path="images/Hands-On-AWS-Project-Deploy-Your-First-Crypto-App/Monolith-to-Microservice-design/Setup-service-on-ECS-for-login-application/amazon-ecs-dashboard-productioncluster-details.jpg" />
</Frame>

## 2. Create the Service from the Cluster

1. Go to **Clusters** and select your production cluster.
2. Click **Create** to create a new service.
3. Select the task definition you created for the login app.
4. Give the service a name such as `login-app-microservice`.

## 3. Configure Load Balancing (Application Load Balancer)

* Under **Load balancing**, choose **Application Load Balancer (ALB)**.
* You can select an existing load balancer or create a new one:
  * If creating new, give the ALB a name and set the idle timeout to `30` seconds.
  * Configure a listener for port `5000` and map it to the target group used by the ECS service.
* Ensure the target group uses the correct port (`5000`) and a health check path that your app responds to (e.g., `/` or `/health`).

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/1ccKtG7aZllQmXlF/images/Hands-On-AWS-Project-Deploy-Your-First-Crypto-App/Monolith-to-Microservice-design/Setup-service-on-ECS-for-login-application/aws-management-console-ecs-load-balancing.jpg?fit=max&auto=format&n=1ccKtG7aZllQmXlF&q=85&s=0dcc1cf3e29b23acc6577641d7e037b8" alt="This image shows the AWS Management Console interface, specifically within the Elastic Container Service (ECS) section, focusing on configuring a service with options for load balancing." width="1920" height="1080" data-path="images/Hands-On-AWS-Project-Deploy-Your-First-Crypto-App/Monolith-to-Microservice-design/Setup-service-on-ECS-for-login-application/aws-management-console-ecs-load-balancing.jpg" />
</Frame>

<Callout icon="warning" color="#FF6B6B">
  If you encounter a subnet error while creating the load balancer, it typically means you selected subnets that are not reachable from the ALB (for example, private-only subnets). Remove private-only subnets or include public subnets that have routes to an Internet Gateway, then retry.
</Callout>

## 4. Wait for Deployment and Verify Health

* After creating the service, ECS launches tasks and registers them with the ALB target group.
* Wait until the service deployment becomes STABLE and the tasks report as *healthy*.
* If the deployment fails or stays unhealthy, check:
  * ECS service events for error messages.
  * Task logs in CloudWatch (or the container logs).
  * ALB target group health check results.
  * Security groups: ensure ALB can reach container port `5000` and the ALB has an inbound rule for the client port you will use.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/1ccKtG7aZllQmXlF/images/Hands-On-AWS-Project-Deploy-Your-First-Crypto-App/Monolith-to-Microservice-design/Setup-service-on-ECS-for-login-application/aws-management-console-ecs-login-app.jpg?fit=max&auto=format&n=1ccKtG7aZllQmXlF&q=85&s=25563c35f459bd025c394cc2879eea49" alt="This image shows the AWS Management Console for Amazon Elastic Container Service (ECS), indicating that the &#x22;login-app-microservice&#x22; is active and running with a healthy status." width="1920" height="1080" data-path="images/Hands-On-AWS-Project-Deploy-Your-First-Crypto-App/Monolith-to-Microservice-design/Setup-service-on-ECS-for-login-application/aws-management-console-ecs-login-app.jpg" />
</Frame>

## 5. Validate the Application

1. In the ECS service page, click **View Load Balancer** for this service.
2. Copy the Load Balancer DNS name.
3. Open a browser and visit: `http://<LOAD_BALANCER_DNS>:5000` (wrap the DNS placeholder in backticks as shown).

Note: The UI may load but login or navigation might fail if the app issues redirects to a hard-coded IP address. The application should use relative paths or environment-aware base URLs so it works behind a load balancer.

## Common ECS/ALB settings (recommended)

| Resource                   | Recommended setting                                               | Notes                                                            |
| -------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------- |
| Container port             | `5000`                                                            | Map this in the task definition container settings.              |
| ALB idle timeout           | `30` seconds                                                      | Adjust if requests may take longer.                              |
| Target Group protocol/port | `HTTP` / `5000`                                                   | Health check path should match an endpoint that returns 200.     |
| Security groups            | ALB: inbound client port (e.g., 80/5000); ECS tasks: allow ALB SG | Ensure ALB SG can reach task SG on port `5000`.                  |
| Subnet selection           | Public subnets for ALB; tasks in private/public as appropriate    | ALB must be in public subnets with route to an Internet Gateway. |

## Troubleshooting checklist

* Subnet selection error: ensure ALB subnets are public or reachable.
* ALB target health failing: check health check path and container response.
* No response in browser: verify security group inbound rules and that ALB is listening on the expected port.
* Task keeps restarting: inspect container logs for exceptions and verify environment variables, database connectivity, and required secrets.

## 6. Fix the Flask redirect issue

If login UI loads but navigation or login redirects fail, inspect the Flask code. Avoid hard-coded external IP addresses in redirects. Use relative paths or configure the base URL via environment variables.

Example (app.py):

```python theme={null}
from flask import Flask, redirect

app = Flask(__name__)

@app.route('/product')
def product():
    # Original (hardcoded external IP):
    # return redirect("http://35.156.49.246:5000/welcomepage")
    # Recommended: use a relative path (keeps redirects within the same host/load balancer)
    return redirect('/welcomepage')
```

<Callout icon="lightbulb" color="#1CB2FE">
  Do not hardcode IP addresses in redirects. Use relative paths (e.g., `redirect('/welcomepage')`), environment-configured base URLs, service discovery, or the load balancer DNS (`http://<LOAD_BALANCER_DNS>:5000`) so the application remains portable and resilient to infrastructure changes.
</Callout>

## Next steps and best practices

* Use environment variables for service URLs and external endpoints rather than hard-coded values.
* Configure health checks that match actual application endpoints and response times.
* Centralize logs in CloudWatch and set up alerts for unhealthy targets or repeated task restarts.
* Consider using HTTPS with a certificate on the ALB for secure traffic.
* For production, consider placing tasks in private subnets and using the ALB in public subnets only.

Useful references:

* [Amazon ECS documentation](https://docs.aws.amazon.com/ecs/latest/developerguide/what-is-ecs.html)
* [Amazon ECR documentation](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)
* [ALB documentation and target groups](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)
* [Flask documentation](https://flask.palletsprojects.com/)

We will cover connecting the product page and login page across services and discuss best practices for environment variables and service discovery in a deployed environment in the next lesson.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/building-scalable-microservices-on-aws-deploy-a-crypto-app/module/d14608f9-c900-4ec7-9bdd-ed8e215da540/lesson/860877dc-f67a-4dff-8ada-536691e7ece9" />
</CardGroup>
