In order to deploy a Java application into AWS ECS (Elastic Container Service) using Terraform, we need to consider a few different things.

Step 1 - Java Application

Create a file called HelloWorld.java and add the following code to it:

1
2
3
4
5
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

We now need to build our class as follows:

1
javac HelloWorld.java

Once this is done, we can package our application into a jar file:

1
jar cvf my-app.jar HelloWorld.class

Step 2 - Dockerfile

Next create a file called Dockerfile and copy the following code into it:

1
2
3
4
5
6
7
FROM openjdk:11-jre-slim

WORKDIR /app

COPY target/my-app.jar /app

CMD ["java", "-jar", "my-app.jar"]

Note that target/my-app.jar in this code is the relative path from the Dockerfile to the my-app.jar that we packaged in step 1 above.

Step 3 - Terraform

Next we will focus on the Terraform. To do this, we can either create different Terraform files, but in this example, we will simply create a single file called main.tf.

In this file, we will first create an ECS task definition:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
resource "aws_ecs_task_definition" "my_task_definition" {
  family                   = "my-task-definition"
  container_definitions    = jsonencode([
    {
      name      = "my-container"
      image     = "my-docker-image"
      cpu       = 256
      memory    = 512
      portMappings = [
        {
          containerPort = 8080
          hostPort      = 8080
        }
      ]
    }
  ])
}

Followed by an ECS service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
resource "aws_ecs_service" "my_service" {
  name            = "my-service"
  cluster         = aws_ecs_cluster.my_cluster.id
  task_definition = aws_ecs_task_definition.my_task_definition.arn
  desired_count   = 1

  network_configuration {
    subnets          = [aws_subnet.my_subnet.id]
    security_groups  = [aws_security_group.my_security_group.id]
    assign_public_ip = true
  }
}

Step 4 - Running the Terraform

Now we need to run the Terraform code, which we can do from the terminal as follows:

1
2
terraform init
terraform apply