Create Dockerfile and Generate Docker Image

Create Task

  1. First, you need to create a task in the build.gradle file by copying the following code block:
tasks.register("unpack", Copy) {
	dependsOn bootJar
	from(zipTree(tasks.bootJar.outputs.files.singleFile))
	into("build/libs")
}

This code defines a Gradle task named “unpack” that copies files from a ZIP archive generated by the “bootJar” task and extracts them into the “build/libs” directory.

Architect

Create .dockerignore File

  1. Create a .dockerignore file to specify files and directories that Docker should ignore when building a Docker image from your project components.

Architect

  1. Copy the code below:
.git
.gitignore
.dockerignore
.gradle
.idea

Dockerfile
README.md

Architect

Create file Dockerfile

  1. Create a Dockerfile and copy the code below:
FROM eclipse-temurin:21-jdk-alpine
VOLUME /tmp
ARG DEPENDENCY=build/libs
COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY ${DEPENDENCY}/META-INF /app/META-INF
COPY ${DEPENDENCY}/BOOT-INF/classes /app
EXPOSE 8081
ENTRYPOINT ["java", "-cp", "app:app/lib/*", "com.firstcloudjourney.productsservice.ProductsserviceApplication"]

Architect

Generate Docker Image

  1. Next, let’s configure IntelliJ to generate a Docker image:
    • Click on the Run icon and select New Run Configuration.

Architect

  1. A popup will appear where we’ll configure as follows:
    • For Image Tag, enter productsservice:1.0.0.
    • Click Modify Options, then select Build options.
    • Once Build options appears, enter --platform linux/amd64.

Architect

  1. Next, we need to configure Before Launch:
    • Click the + icon and select Run Gradle Task.
    • Then a popup will appear as shown below:

Architect

  1. In the popup for Select Gradle Task:
    • For Gradle project, choose productsservice.
    • For Task, select the unpack task that we added earlier.
    • Click OK.

Architect

  1. After returning to the Edit Configuration popup, click Apply.

Architect

Build Application using BootJar

  1. Next, let’s build the application using bootJar from Gradle:
    • Click on the Gradle icon.
    • Choose Tasks, then build, and finally click bootJar to build the application.

Architect

  1. Check the built application file located in build/libs.

Architect

Generate Docker Image

  1. Now, let’s create a Docker image from the built application:
    • Click on the Run icon on the Dockerfile and choose Build image for ‘DockerFile’.

Make sure you have Docker Desktop running to successfully build the image.

Architect

  1. After successfully creating the image, you should see productsservice:1.0.0 generated.

Architect