Software Engineering

How to Deploy a Java Application in AWS ECS using Terraform


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:

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

We now need to build our class as follows:

javac HelloWorld.java

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

jar cvf my-app.jar HelloWorld.class

Step 2 – Dockerfile

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

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:

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:

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:

terraform init
terraform apply