01: Docker tutorial with Java & Maven

Pre-requisite: Docker is installed on your machine for Mac OS X (E.g. $ brew cask install docker) or Windows 10. Docker interview Q&As.

Step 1: Create a Java project “docker-test” with “HelloDocker.java” file under “src/main/java” in a package named “com/mypkg”, and “pom.xml” in the base project folder. Using the Visual Studio Code editor.

Basic Mavenized Java folder structure with Dockerfile

HelloDocker.java
pom.xml

Step 2: Create a “Dockerfile” in the project base directory.

Dockerfile

Step 3: Docker has two steps. Firstly, “build” an image based on the “Dockerfile” and then “run” the container, which is an instance of the image.

From the docker-test folder build the image

it uses the “Dockerfile” in the “.” (i.e. current directory)

once the docker image is built, you can list it with

It has built an image of size 119MB. The image name will be “docker-test:latest”

You can remove an image with “docker rmi 25a4f7356b10”.

From the docker-test create a container, which is an instance of the image

Present working directory is mapped to Docker container’s “/app” and synchronised.

Now, you are in the Docker container prompt

Step 4: You can run “mvn package” to build the jar file “hellodocker-1.0.jar” in “target” folder.

After packaging, there will be a target folder with “hellodocker-1.0.jar” file.

After packaging.

“-v “$(pwd):/app:consistent” keeps the folders & files in the Docker container in the “/app” folder in sync with the current working directory “docker-test” shown above.

Step 5: Run the “hellodocker-1.0.jar”

Output:

You could also have directly run

Create an image

Create a container, which is an instance of the image

Notes: Look at the “Docker hub” for the images that you can use.

GNU make file to automate docker runs

Assumes that GNU Make is installed on your machine.

Step 6: Create a “Makefile” in the base project folder.

Docker with makefile

Makefile

You can run the commands like:

If you want to run the app, just execute


800+ Java & Big Data Interview Q&As

Top