Joel Neubeck
Joel Neubeck

Reputation: 87

ECS Fargate / single ALB / multiple docker containers

Does anyone have an example of how I could build up an ECS cluster with a single application load balancer forwarding host header request to two different docker containers.

I want to have one ALB for A single ESC cluster running both my angular site as well as a.net web service. Ultimately my goal is to script this in terraform.

Upvotes: 2

Views: 1936

Answers (1)

Alessandro
Alessandro

Reputation: 33

Without knowing all the information I think that you are looking for path-based routing or even better host-based routing.

Terraform

You need an aws_lb_listener_rule (Load Balancer Listener Rule) for each host/path. You need an aws_alb_target_group for each ECS services and you refer the correct target group inside the resource aws_lb_listener_rule.

General

Listener Rules

Before you start using your Application Load Balancer, you must add one or more listeners. A listener is a process that checks for connection requests, using the protocol and port that you configure. The rules that you define for a listener determine how the load balancer routes request to the targets in one or more target groups. docs

Use Path-Based Routing with Your Application Load Balancer

https://docs.aws.amazon.com/en_us/elasticloadbalancing/latest/application/tutorial-load-balancer-routing.html

Examples

Host Based Listener Rule

resource "aws_lb_listener_rule" "host_based_routing" {
  listener_arn = aws_lb_listener.front_end.arn
  priority     = 99

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.static.arn
  }

  condition {
    field  = "host-header"
    values = ["my-service.*.terraform.io"]
  }
}

Where the conditions block define the host or the pattern (example below) where request must be sent.

Path Based Listener Rule

resource "aws_lb_listener_rule" "static" {
  listener_arn = aws_lb_listener.front_end.arn
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.static.arn
  }

  condition {
    field  = "path-pattern"
    values = ["/static/*"]
  }
}

Target group

resource "aws_alb_target_group" "alb_target_group" {
  name                 = "example-target-group"
  protocol             = "HTTP"
  port                 = var.exposed_port
  vpc_id               = var.vpc_id
  deregistration_delay = 30
  health_check {
    path    = var.service_health_check_path
    matcher = "200-399"
  }
}

https://www.terraform.io/docs/providers/aws/r/lb_listener_rule.html https://www.terraform.io/docs/providers/aws/r/lb_target_group.html

Upvotes: 2

Related Questions