Why can these ECS services not communicate?

Hello! I have a small project i am trying to deploy to aws. I’ve tried a few different configurations, and am currently trying to deploy to ECS.

The project works fine using Docker Compose locally, as well as using the Docker Compose AWS context. However, apparently this has been depricated, so i dont want to base a future CI/CD pipeline on it, so im working on getting setup with terraform.

Honestly im no cloud expert so im mostly trying to replicate what Docker produces, as i know that works. When deploying what ive got working with Terraform so far though, the server container cannot reach the database container, it should be able to on db. Everything spins up fine, but the container keeps sending requests, getting no response, till it falls over. Seeing as the Docker Compose deployment to AWS works fine, and Terraform deploys without any errors, I’m pretty sure the issue is with my infrastrucure.

Now I’ve tried a bunch of things to get it working, but from looking at any docs i can find, ive got everything setup correctly, so its mostly been trial and error! This has got me nothing but a headache, so i think its time to ask someone who actually knows what theyre talking about. So, here is the github repo https://github.com/FegrusB/SBQuizServer/tree/terraform and bellow im going to copy what i think is the closet to correct itteration so far. Thanks for your help!

resource "aws_default_vpc" "vpc" {
  enable_dns_support   = true
  enable_dns_hostnames = true
}

resource "aws_default_subnet" "default_subnet_a" {
  availability_zone = var.availability_zones[0]
}

resource "aws_default_subnet" "default_subnet_b" {
  availability_zone = var.availability_zones[1]
}

resource "aws_default_subnet" "default_subnet_c" {
  availability_zone = var.availability_zones[2]
}

resource "aws_service_discovery_private_dns_namespace" "quiz_private_namespace" {
  name        = "quiz.server.local"
  description = "Namespace for quiz services"
  vpc         = aws_default_vpc.vpc.id
}
/*
resource "aws_service_discovery_service" "quiz_db_sd_record" {
  name = "db"

  dns_config {
    namespace_id = aws_service_discovery_private_dns_namespace.quiz_namespace.id

    dns_records {
      ttl  = 10
      type = "A"
    }

    routing_policy = "MULTIVALUE"
  }

  health_check_custom_config {
    failure_threshold = 1
  }
}

resource "aws_service_discovery_service" "quiz_sb_server_sd_record" {
  name = "sb-server"

  dns_config {
    namespace_id = aws_service_discovery_private_dns_namespace.quiz_namespace.id

    dns_records {
      ttl  = 10
      type = "A"
    }

    routing_policy = "MULTIVALUE"
  }

  health_check_custom_config {
    failure_threshold = 1
  }
}

resource "aws_ecs_cluster" "quiz_cluster" {
  name = var.quiz_cluster_name

  setting {
    name  = "containerInsights"
    value = "disabled"
  }
}

resource "aws_ecs_task_definition" "quiz_db_task" {
  family                   = "quiz-db"
  container_definitions    = <<DEFINITION
[
        {
            "name": "db",
            "image": "${var.ecr_repo_url}:db",
            "cpu": 0,
            "links": [],
            "portMappings": [{
              "name": "dbport",
              "containerPort": 3306,
              "hostPort": 3306,
              "protocol": "tcp"
            }],
            "essential": true,
            "entryPoint": [],
            "command": [],
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "linuxParameters": {
                "devices": [],
                "tmpfs": []
            },
            "secrets": [],
            "dependsOn": [
                {
                    "containerName": "Db_ResolvConf_InitContainer",
                    "condition": "SUCCESS"
                }
            ],
            "dnsServers": [],
            "dnsSearchDomains": [],
            "extraHosts": [],
            "dockerSecurityOptions": [],
            "dockerLabels": {},
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "quiz-db-logs",
                    "awslogs-region": "eu-west-2",
                    "awslogs-stream-prefix": "dbquiz"
                },
                "secretOptions": []
            },
            "systemControls": [],
            "credentialSpecs": []
        },
        {
            "name": "Db_ResolvConf_InitContainer",
            "image": "docker/ecs-searchdomain-sidecar:1.0",
            "cpu": 0,
            "links": [],
            "portMappings": [],
            "essential": false,
            "entryPoint": [],
            "command": [
                "eu-west-2.compute.internal",
                "sbquizserver.local"
            ],
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "secrets": [],
            "dnsServers": [],
            "dnsSearchDomains": [],
            "extraHosts": [],
            "dockerSecurityOptions": [],
            "dockerLabels": {},
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "quiz-db-logs",
                    "awslogs-region": "eu-west-2",
                    "awslogs-stream-prefix": "dbquizinit"
                },
                "secretOptions": []
            },
            "systemControls": [],
            "credentialSpecs": []
        }
    ]
  DEFINITION
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  memory                   = "512"
  cpu                      = "256"
  execution_role_arn       = aws_iam_role.quiz_task_execution_role.arn
}

resource "aws_ecs_task_definition" "quiz_sb_server_task" {
  family                   = "quiz-sb-server"
  container_definitions    = <<DEFINITION
  [

        {
            "name": "sb-server",
            "image": "fegrus/quiz-sb-server:latest",
            "cpu": 0,
            "links": [],
            "portMappings": [
                {
                    "name": "sb-port",
                    "containerPort": 8080,
                    "hostPort": 8080,
                    "protocol": "tcp"
                }
            ],
            "essential": true,
            "entryPoint": [],
            "command": [],
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "linuxParameters": {
                "devices": [],
                "tmpfs": []
            },
            "secrets": [],
            "dependsOn": [
                {
                    "containerName": "Sbserver_ResolvConf_InitContainer",
                    "condition": "SUCCESS"
                }
            ],
            "dnsServers": [],
            "dnsSearchDomains": [],
            "extraHosts": [],
            "dockerSecurityOptions": [],
            "dockerLabels": {},
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "quiz-sb-server-logs",
                    "awslogs-region": "eu-west-2",
                    "awslogs-stream-prefix": "sbquizserver"
                },
                "secretOptions": []
            },
            "systemControls": [],
            "credentialSpecs": []
        },
        {
            "name": "Sbserver_ResolvConf_InitContainer",
            "image": "docker/ecs-searchdomain-sidecar:1.0",
            "cpu": 0,
            "links": [],
            "portMappings": [],
            "essential": false,
            "entryPoint": [],
            "command": [
                "eu-west-2.compute.internal",
                "sbquizserver.local"
            ],
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "secrets": [],
            "dnsServers": [],
            "dnsSearchDomains": [],
            "extraHosts": [],
            "dockerSecurityOptions": [],
            "dockerLabels": {},
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "quiz-sb-server-logs",
                    "awslogs-region": "eu-west-2",
                    "awslogs-stream-prefix": "sbquizserver-init"
                },
                "secretOptions": []
            },
            "systemControls": [],
            "credentialSpecs": []
        }
    ]
  DEFINITION
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  memory                   = "512"
  cpu                      = "256"
  execution_role_arn       = aws_iam_role.quiz_task_execution_role.arn
}
resource "aws_cloudwatch_log_group" "log_db_group" {
  name = "quiz-db-logs"

  tags = {
    Environment = "production"
    Application = "quiz"
  }
}
resource "aws_cloudwatch_log_group" "log_sb_server_group" {
  name = "quiz-sb-server-logs"

  tags = {
    Environment = "production"
    Application = "quiz"
  }
}
resource "aws_iam_role" "quiz_task_execution_role" {
  name               = var.ecs_task_execution_role_name
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

resource "aws_iam_role_policy_attachment" "ecs_task_execution_role_policy" {
  role       = aws_iam_role.quiz_task_execution_role.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

resource "aws_lb_target_group" "target_group" {
  name        = var.target_group_name
  port        = var.container_port
  protocol    = "HTTP"
  target_type = "ip"
  vpc_id      = aws_default_vpc.vpc.id
}

resource "aws_alb" "application_load_balancer" {
  name               = var.application_load_balancer_name
  load_balancer_type = "application"
  subnets = [
    "${aws_default_subnet.default_subnet_a.id}",
    "${aws_default_subnet.default_subnet_b.id}",
    "${aws_default_subnet.default_subnet_c.id}"
  ]
  security_groups = ["${aws_security_group.load_balancer_security_group.id}"]
}

resource "aws_security_group" "load_balancer_security_group" {
  ingress {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_lb_listener" "listener" {
  load_balancer_arn = aws_alb.application_load_balancer.arn
  port              = "8080"
  protocol          = "HTTP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.target_group.arn
  }
}

resource "aws_security_group" "service_security_group" {
  ingress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    security_groups = ["${aws_security_group.load_balancer_security_group.id}"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_ecs_service" "quiz_sb_server_service" {

  name            = var.quiz_sb_server_service_name
  cluster         = aws_ecs_cluster.quiz_cluster.id
  task_definition = aws_ecs_task_definition.quiz_sb_server_task.arn
  launch_type     = "FARGATE"
  desired_count   = 1

  propagate_tags      = "SERVICE"
  scheduling_strategy = "REPLICA"

  force_new_deployment = true
  triggers = {
    redeployment = plantimestamp()
  }

  network_configuration {
    subnets          = ["${aws_default_subnet.default_subnet_a.id}", "${aws_default_subnet.default_subnet_b.id}", "${aws_default_subnet.default_subnet_c.id}"]
    assign_public_ip = true
    security_groups  = ["${aws_security_group.service_security_group.id}"]
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.target_group.arn
    container_name   = "sb-server"
    container_port   = var.container_port
  }

  service_registries {
    container_port = "0"
    port           = "0"
    registry_arn   = aws_route53_record.tfer--Z0073158MH8B1HP1BV9A_sb-002D-server-002E-sbquizserver-002E-local-002E-_A_2fec373d9d034a70b5a20f6896180167.id
  }
}

resource "aws_ecs_service" "quiz_db_service" {

  name            = var.quiz_db_service_name
  cluster         = aws_ecs_cluster.quiz_cluster.id
  task_definition = aws_ecs_task_definition.quiz_db_task.arn
  launch_type     = "FARGATE"
  desired_count   = 1

  propagate_tags      = "SERVICE"
  scheduling_strategy = "REPLICA"

  service_registries {
    container_port = "0"
    port           = "0"
    registry_arn   = aws_route53_record.tfer--Z0073158MH8B1HP1BV9A_db-002E-sbquizserver-002E-local-002E-_A_151ff0421bbf47b7bcc149aaacb53a0d.id
  }

  force_new_deployment = true
  triggers = {
    redeployment = plantimestamp()
  }

  network_configuration {
    subnets          = ["${aws_default_subnet.default_subnet_a.id}", "${aws_default_subnet.default_subnet_b.id}", "${aws_default_subnet.default_subnet_c.id}"]
    assign_public_ip = true
    security_groups  = ["${aws_security_group.service_security_group.id}"]
  }
}

your security group should allow access from self to the necessary ports, currently it only allows access from the LB

Overriding the database URL? My understanding is that if i have ECS service discovery setup right, i should just be able to use the server name, as i would with docker. Is that incorrect?

Yeah sorry, I haven’t used service discovery before with ECS. I assume it will add a DNS record to your ECS task IP address so in this case yes, you would need to allow access from self in the security group for the DB port.

No problem, thanks for the help! So just adding something like this to the service sg? Doesnt look like its worked.

ingress {
    from_port   = 3306
    to_port     = 3306
    protocol    = "TCP"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 3306
    to_port     = 3306
    protocol    = "TCP"
    cidr_blocks = ["0.0.0.0/0"]
  }

Any particular reason you decided to go with two ECS task definitions instead of just one?

From what I’ve seen I think thats the correct way to do it, so the services can scale independantly (once i get to that in 2035).

Ah good point.

I haven’t read all your code, but with ECS service discovery I believe the DNS resolves to . with the namespace being your cluster name by default. So you’d need to have your frontend service call db.quiz-cluster rather than db. You also need to enable DNS support in your VPC if you haven’t already.

I’m not 100% sure it does use .. When deploying using the Docker Compose context, the url is still set in my Spring Boot config as just db, yet it works. From what i can see i dont think its changed anywhere. Either way, ive tried this, and dont think its worked. Thanks though!

If you deploy as compose wouldn’t it be a single task then and in that case it would be locally available?

I was using the container name with docker rather than localhost (so db) when composing to AWS it created a separate ECS service for each container, using service discovery.

IIRC, u/likeavirgil was on the right track, the service names need the service discovery namespace as the TLD.

DNS records for a service discovery service can be queried within your VPC. They use the following format: ..

Here’s a resource that may be helpful: https://containersonaws.com/pattern/service-discovery-fargate-microservice-cloud-map

So I’ve restarted based on these blueprints https://github.com/aws-ia/ecs-blueprints. Also I’ve added an env variable, overriding the db url, into the format you suggest. However the containers still cannot connect. Any ideas what else it could be?

Have you tried using vpc reachability analyzer? It’s a wonderful tool to debug network connectivity