Building and running a Docker container for a Java application
There are different ways to build a Docker image locally of your Java application and start a container.
This one is more of a step-by-step guide, which can also be automated by a local script. If you want you can also move the build steps into the Dockerfile, if it doesn’t give you any conflicts in a pipeline.
The Dockerfile
First, create a Dockerfile in the root of your project. Consider to choose the right JDK version for your project.
FROM openjdk:17
COPY ./build/libs/configmap-demo-0.0.1-SNAPSHOT.jar ./src/
WORKDIR /src
CMD ["java", "-jar", "./configmap-demo-0.0.1-SNAPSHOT.jar"]
In this case configmap-demo is the project name. When you’re using Gradle you can find this in the settings.gradle.
The suffix is the value of the version key found in the build.gradle.
Build your application
Build your application, so that you can find the jar in the build/libs directory.
Either run the Gradle build Task in the Gradle tab of IntelliJ or execute it in your CLI:
gradle build

Build Docker image
Execute the build command in the root directory of your project:
docker build . -t configmap-demo-v1
Run Docker container
Run a container out of your image.
docker run configmap-demo-v1

Done!