user998692 user998692 - 3 months ago 18
Java Question

What should a dockerfile contain to run a simple CRUD web application?

I am studying Docker and to understand better, I want to use it to run a Java web application that I created a while ago. It uses Java, Spring, Hibernate on back-end and Spring MVC on front-end, and MySQL as a database. In Eclipse, it can be easily run on Tomcat and opened in a browser. In essence, it's a simple CRUD application.

In order to create a dockerfile to run it, do I need to start with (FROM) an OS image? How do I include Java, MySQL and Tomcat instances? How can I configure it to run the application war?

Answer

The standard Docker style is to have a single service per container and then have an orchestration tool manage the containers as a group.

Docker comes with a tool called Docker Compose that is configured with a docker-compose.yml file.

version: '2'

services:
  myapp_web:
    build: ./web/
    ports:
     - "8080:8080"
    networks:
     - myapp_net

  myapp_db:
    build: ./db/
    volumes:
     - myapp_data:/var/lib/mysql
    networks:
     - myapp_net

volumes:
  myapp_data:

networks:
  myapp_net:
    driver: bridge

Dockerfile

It will be easiest if you start your Dockerfiles from existing images so you don't have to deal with complete builds. Most popular open source software will have images available on Docker Hub. Searching " docker" will normally be the top result. Have a look at the Dockerfile from the images you use. The official images tend to use all the current best practices.

The mysql image gives you a blank mysql installation with some custom configuration options. You might not need a Dockerfile here initially.

./db/Dockerfile

FROM mysql:5.7
RUN some-setup.sh

The tomcat image supplies a working OpenJDK and Tomcat installation for you to deploy your app to.

./web/Dockerfile

FROM 8.0-jre8-alpine
COPY myapp.war /usr/local/tomcat/webapps/myapp.war