[Java] How to deploy kotlin(java) app with AWS fargate

1 minute read

Point

  • If the amount of memory specified in the “task memory” of the fargate task definition is exceeded, the task will be killed.
  • Therefore, it is necessary to adjust the maximum heap size etc. so that the task memory is not exceeded.

Environment

  • Language: Kotlin
  • Framework: ktor
  • docker image: openjdk:8-jre-alpine

Dockerfile

FROM openjdk:8-jre-alpine

ENV APPLICATION_USER ktor
RUN adduser -D -g `` $APPLICATION_USER

RUN mkdir /app
RUN chown -R $APPLICATION_USER /app

USER $APPLICATION_USER

COPY ./build/libs/my-application.jar /app/my-application.jar
WORKDIR /app

CMD ["java", "-server", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseCGroupMemoryLimitForHeap", "-XX:InitialRAMFraction=2", "-XX:MinRAMFraction=2", "-XX:MaxRAMFraction =2", "-XX:+UseG1GC", "-XX:MaxGCPauseMillis=100", "-XX:+UseStringDeduplication", "-XX:MaxMetaspaceSize=256M", "-XshowSettings:vm", "-jar", "my-application.jar"]

Basically doctor of ktor, but added java option.

  • -XX:MaxMetaspaceSize=256M: It is a setting that secures the maximum metaspace value of 256MB and does not increase it any more. By default, it can be expanded indefinitely, so I set the maximum value just in case.
  • -XshowSettings:vm: Output VM settings at startup.

fargate task definition

Be sure to specify the hard memory limit in the container definition. The value specified here is passed to the --memory option of docker run. Normally, specify the same value as the task memory.

![Screenshot 2020-08-27 16.08.00.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/9875/9c10efd2-022f-067a-f4e3-(c32e627308b6.png)

Check task log

Display the Fargate task log and confirm that the Max. Heap Size is at the expected value. In this case, the hard limit is 1000MiB and the java option is “-XX:MaxRAMFraction=2”, so 500M is correct.

![Screenshot 2020-08-27 15.39.23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/9875/15658c35-8e8d-df78-dd6c-(a1c72537e067.png)

Reference