We are going to use an application that was created in this article. It is using Spring 5 and it implements a simple REST API controller GET /hello that returns Hello string as a reponse. Lets get this jar file in case we don't want to build the application now.
Lets create the following directory structure with all the required files before we start.
Now we want to create Dockerfile that will create an image with demo.jar. When we start that docker image, we want to start the Sprint REST API on port 8080. Study the documentation what each docker instruction does.
Once build is done, we can star the docker. Study the documentation to learn how docker run works with all the options. Here we use -d flag to run container in detached mode. -p flag says port mapping, from docker container to our system.
First, check if our docker container is running.
If the docker container is up, we can try to talk to the server which is started inside the docker container.
Lets connect to the docker container and explore what is there.
To explore what exactly has happened, we can run the container in interactive mode.
The consequent question is how to stop the docker container we just started. We need do it by using container id, or at least the begging of the id string. e13 should be enough to identify the docker container and stop it.
Find application jar based on a pattern
When we include version number in a .jar file, we need to be able to find it dynamically in docker and pass it to java -jar as a parameter.
We can create this script, which we copy into docker image. It will find a jar file based on a pattern we define and then uses this file as parameter for java program to start the server.
➜ hello-world docker build -t spring/rest-api .
Sending build context to Docker daemon 15.85MB
Step 1/1 : FROM openjdk:8u151-jre-slim
---> 66d599bf7861
Successfully built 66d599bf7861
Successfully tagged spring/rest-api:latest
➜ docker run -d -p 8080:8080 spring/rest-api
e13dfb803fb264fe61767f0378cda2029debad8488a597a22a9e6100fbcebd5e
➜ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e13dfb803fb2 spring/rest-api "java -jar demo.jar" About a minute ago Up About a minute 0.0.0.0:8080->8080/tcp nervous_ardinghelli