DEV Community

Cover image for Kubernetes for Java Developers - Creating a docker image
Sandro Giacomozzi
Sandro Giacomozzi

Posted on • Updated on

Kubernetes for Java Developers - Creating a docker image

Welcome back

On first tutorial of this series, we learn about set up a local kubernetes environment.
At this point, we have a Java application that uses a mysql database running on docker.
To package our application inside a docker image, we need to create a Dockerfile.

Create a Dockerfile

Dockerfile definition:

FROM openjdk:11.0.3-jdk-slim
RUN mkdir /usr/myapp
COPY target/java-kubernetes-0.0.1-SNAPSHOT.jar /usr/myapp/app.jar
WORKDIR /usr/myapp
CMD ["java", "-Xms128m", "-Xmx256m", "-jar", "app.jar"]

Use Make to automate tasks

Make is a tool which controls the generation of executables and other non-source files of a program from the program's source files.
We will use make to automate maven and docker commands in this project.
Check your make installation. Type make --version on terminal. If none happens, please install make before continue.

Create a Makefile

Creating a Makefile on the same Dockerfile directory.
Check out the complete Makefile on github:

The importance parts are:

    mvn clean install; \
    docker build --force-rm -t java-k8s .

    make stop-db; \
    make rm-db; \
    docker run --name mysql57 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_USER=java -e MYSQL_PASSWORD=1234 -e MYSQL_DATABASE=k8s_java -d mysql/mysql-server:5.7

    make stop-app; \
    make rm-app; \
    docker run --name myapp -p 8080:8080 -d -e DATABASE_SERVER_NAME=mysql57 --link mysql57:mysql57 java-k8s:latest      

build: Run maven and create a docker image with the name "java-k8s"
run-db: Start a new mysql database container
run-app: Start a new application container

In this order, type:

make build
make run-db
make run-app

Obs: Wait 30 seconds between run:db and run:app to make time to start up database.

To see logs of applicaton, type:

docker logs -f myapp

And CTRL+C to exit log mode.

Type docker ps to see the containers running


To stop applicaton and database, type:

make stop-app
make stop-db

Please clone the complete demo app at:

Have fun!

See you on the next part. Deploy your app into kubernetes cluster.

Top comments (0)