I spend last couple weeks working on java apps running within docker containers deployed on clustered CoreOS machines. It’s pretty simple to run java app within a docker container. You just have to choose a base image for your app and write a docker file.
Note that docker registry contains many java distributions usually based on open jdk. We use our internal image for Oracle’s Java 8, build on top of something like this docker file. Once you make a decision whether oracle or openjdk, you can start to write your own docker file.
ADD your.jar /opt/your-app
ADD /dependencies /opt/your-app/dependency
CMD [“java -jar /opt/your-app/your.jar”]
However, your app would probably require some parameters. Therefore, last line usually calls your shell script. Such script than validates number and format of those parameters among other things. This is also useful during the development phase because none of us want to build and start an image always when something gets changed and you need to test it. So the last line of your docker file is usually similar to next snippet:
So far so good. Let say that I’ve just developed my code and made integration tests working. Once you are satisfied with your solution, you try something like this:
sudo docker run –name you-app-name your-image -e ENVIRONMENT_PARAM=VALUE …
sudo docker stop your-app-name
Spring boot omits boiler-plate code and does a lot of things you eventually should do too, see documentation. I based my Main class on CommandLineRunner and I have to admit that the application or main itself is one of shortest main methods I have ever wrote.
New problem appeared once I tried to stop application. My process should receive SIGTERM and than SIGKILL according to the documentation. Nice thing about spring boot is automatic shutdown hook registered within your application. Unfortunately application log content obtained via docker logs showed that there was no such thing like …
SIGTERM, and after a grace period,
… the docker deamon just killed my app. Short research gave me a clue as signals are not distributed in child bash scripts. I finally found interesting article describing issues in java, shell scripts and signals in full details. As I was lucky developer, I just slightly changed last line of shell script to something like:
exec java -jar …
This simple change allows graceful shutdown and my java app can now close running spring context. This transitively means that all registered auto-closable beans are now terminated according to all needs.