28 min read

In this article by Ajitesh Kumar, the author of the book Building Web Apps with Spring 5 and Angular, we will see the key aspects of web request-response handling in relation with Spring Web MVC framework.

In this article, we will go into the details of setting up development environment for working with Spring web applications. Following are going to be the key areas we are going to look into:

  • Installing Java SDK
  • Installing/configuring Maven
  • Installing Eclipse IDE
  • Installing/configuring Apache Tomcat Server
  • Installing/configuring MySQL Database
  • Introducing Docker containers
  • Setting up development environment using Docker-compose

(For more resources related to this topic, see here.)

Installing Java SDK

First and foremost, we will install Java SDK. We will work with Java 8 throughout this book. Go ahead and access this page (http://www.oracle.com/technetwork/java/javase /downloads/jdk8-downloads-2133151.html). Download the appropriate JDK kit. For Windows OS, there are two different versions, one for x86 and another for x64. One should select appropriate version and download “exe” file. Once downloaded, double-click on the executable file. This would start the installer. Once installed, following needs to be done: 

  1. Set the JAVA_HOME as the path where JDK is installed.
  2. Include the path in %JAVA_HOME%/bin in the environment variable. One could do that by adding the %JAVA_HOME%/bin directory to his/her user PATH environment variable by opening up the system properties (WinKey + Pause), selecting the “Advanced” tab, and the “Environment Variables” button, then adding or selecting the PATH variable in the user variables with the value. Once done with the preceding steps, open a shell and type the command, “java – version”. It should print the version of Java you installed just now.

Next, let us try and understand how to install and configure Maven, a tool for building and managing Java projects.

Installing/Configuring Maven

Maven is a tool which can be used for building and managing Java-based project. Following are some of the key benefits of using Maven as a build tool:

  • It provides a simple project setup that follows best practices – Get a new project or module started in seconds.
  • It allows a project to build using its Project Object Model (POM) and a set of plugins that are shared by all projects using Maven, providing a uniform build system.
  • It allows usage of large and growing repository of libraries and metadata to use out of the box.
  • Based on model based builds, it provides ability to work with multiple projects at the same time. Any number of projects can be built into predefined output types such as a JAR, WAR, or distribution based on metadata about the project, without the need to do any scripting in most cases.

One can download Maven from https://maven.apache.org/download.cgi. Before installing Maven, make sure Java is installed and configured (JAVA_HOME) appropriately as mentioned in the previous section. On Windows, you could check the same by typing the command, “echo %JAVA_HOME%”: 

  1. Extract distribution archive in any directory. If it works on Windows, install unzip tool such as WinRAR. Right-click on the ZIP file and unzip it. A directory (with name as “apache-maven-3.3.9”, the version of maven at the time of writing) holding the files such as bin, conf and so on will be created.
  2. Add the bin directory of the created directory, “apache-maven-3.3.9” to the PATH environment variable. One could do that by adding the bin directory to his/her user PATH environment variable by opening up the system properties (WinKey + Pause), selecting the “Advanced” tab, and the “Environment Variables” button, then adding or selecting the PATH variable in the user variables with the value
  3. Open a new shell and type, “mvn -v”. The result should print the Maven version along with details including Java version, Java home, OS name, and so on.

Now, let’s look at how can we create a Java project using Maven from command prompt before we get on to creating a Maven project in Eclipse IDE. Use following mvn command to create a Java project: 

mvn archetype:generate -DgroupId=com.healthapp -DartifactId=HealthApp - DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

With archetype:generate and -DarchetypeArtifactId=maven-archetypequickstart template, following project directory structure is created:fdgrhggv

In the preceding diagram, healthapp folders within src/main and src/test folder consist of a hello world program named as “App.java” and a corresponding test program such as “AppTest.java”. Also, the at the top most folder, a pom.xml file is created.

In the next section, we will install Eclipse IDE and create a maven project using the functionality provided by the IDE.

Installing Eclipse IDE

In this section, we will get ourselves setup with Eclipse IDE, a tool used by Java developers to create Java EE and web applications. Go to Eclipse website, http://www.eclipse.org and download the latest version of Eclipse and install thereafter. As we shall be working with web applications, select the option such as “Eclipse IDE for Java EE Developers” while downloading the IDE.

As you launch the IDE, it will ask to select a folder for workspace. Select appropriate path and start the IDE.

Following are some of the different types of projects developers could work using IDE:

  • A new Java EE Web project
  • A new JavaScript project. This option will be very useful when you are working with standalone JavaScript project and planning to integrate with server components using APIs.
  • Checkout existing Eclipse projects from Git and work on them
  • Import one or more existing Eclipse projects from filesystem or archive

Import existing Maven Project in Eclipse

In previous section, we have created a maven project namely HealthApp. We will now see how we can import this project into Eclipse IDE:

  1.  Click File > import.
  2. Type Maven in the search box under Select an import source.
  3. Select Existing Maven Projects.
  4. Click Next.
  5. Click Browse and select the HealthApp folder which is the root of the Maven project. Note that it contains the pom.xml file.
  6. Click Finish. The project will be imported in Eclipse. Make sure this is how it looks like:

Figure 2: Maven project imported into Eclipse

Let’s also see how one can create a new Maven project with Eclipse IDE.

Create new Maven Project in Eclipse

Follow the instructions given to create new Java Maven project with Eclipse IDE: 

  1. Click File > New > Project.
  2. Type Maven in the search box under Wizards.
  3. Select Maven project.
  4. A dialog box with title as “New Maven Project”, having option “use default Workspace location” as checked, appears.
  5. Make sure that Group Id is selected as org.apache.maven.archetypes with Artifact Id selected as maven-archetype-quickstart.
  6. Give a name to Group Id, say, “com.orgname”. Give a name to Artifact Id, say, “healthapp2”.
  7. Click Finish.

As a result of preceding steps, a new Maven project will be created in Eclipse. Make sure this is how it looks like: Figure 3: Maven project created within Eclipse

In next section, we will see how to install and configure Tomcat Server.

Installing/Configuring Apache Tomcat Server

In this section, we will learn about some of the following:

  • How to install and configure Apache Tomcat server
  • Common deployment approaches with Tomcat server
  • How to add Tomcat server in Eclipse

The Apache Tomcat software is an open source implementation of the Java Servlet, JavaServer Pages (JSPs), Java Expression Language and Java WebSocket technologies. We will work with Apache Tomcat 8.x version in this book. We will look at both Windows and Unix version of Java. One can go to http://tomcat.apache.org/ and download the appropriate version from this page. At the time of installation, it requires you to choose the path to one of the JREs installed on your computer. Once installation is complete, Apache Tomcat server is started as a Windows service. With default installation options, one can then access the Tomcat server by accessing URL such as

A page such as following will be displayed: Figure 4: Apache Tomcat Server Homepage

Following is how Tomcat’s folder structure looks like: Figure 5: Apache Tomcat Folder Structure

In the preceding diagram, note the “webapps” folder which will contain our web apps. The following description uses the variable name such as following:

  • $CATALINA_HOME, the directory into which Tomcat is installed.
  • $CATALINA_BASE, the base directory against which most relative paths are resolved. If you have not configured Tomcat for multiple instances by setting a CATALINA_BASE directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME.

Following are most commonly used approaches to deploy web apps in Tomcat:

  1. Copy unpacked directory hierarchy into a subdirectory in directory $CATALINA_BASE/webapps/. Tomcat will assign a context path to your application based on the subdirectory name you choose.
  2. Copy the web application archive (WAR) file into directory $CATALINA_BASE/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.

Let us learn how to configure Apache Tomcat from within Eclipse. This would be very useful as one could start and stop Tomcat from Eclipse while working with his/her web applications.

Adding/Configuring Apache Tomcat in Eclipse

In this section, we will learn how to add and configure Apache Tomcat in Eclipse. It would help to start and stop the server from within Eclipse IDE.

Following steps need to be taken to achieve this objective:

  1. Make sure you are in Java EE perspective.
  2. Click on “Servers” tab in lower panel. You will find a link saying “No servers are available. Click this link to create a new server…”. Click on this link.
  3. Type “Tomcat” under Select the server type. It would show a list of Tomcat server with different versions. Select “Tomcat v8.5 Server” and click Next.
  4. Select the Tomcat installation directory. Click on “Installed JREs…” button and make sure that appropriate JRE is checked. Click Next.
  5. Click Finish. This would create an entry for Tomcat server in “Servers” tab.
  6. Double-click on Tomcat server. This would open up a configuration window where multiple options such as Server Locations, Server Options, Ports can be configured.
  7. Under Server Locations, click on “Browse Path” button to select the path to “webapps” folder within your local Tomcat installation folder. Once done, save it using Ctrl-S.
  8. Right click on “Tomcat Server” link listed under “Servers” panel and click “Start”.
  9. This should start the server. You should be able to access the Tomcat page on the URL, http://localhost:8080/.

Installing/Configuring MySQL Database

In this section, we will learn on how to install MySQL database. Go to MySQL Downloads site (https://www.mysql.com/downloads/) and click on “Community (GPL) Downloads” under MySQL community edition. On the next page, you will see listing of several MySQL software packages. Download following:

  • MySQL Community Server
  • MySQL Connector for Java development (Connector/J)

Installing/Configuring MySQL Server

In this section, we will see how to download, install and configure the MySQL database and related utility such as MySQL Workbench. Note that MySQL Workbench is a unified visual tool which can be used by database architects, developers and DBA for activities such as data modeling, SQL development, and comprehensive administration tools for server configuration, user administration etc.

Follow the instructions given for installation & configuration of MySQL server and workbench: 

  1. Click on “Download” link under “MySQL Community Server (GPL)” found as first entry on “MySQL Community Downloads” page. We shall be working with Windows version of MySQL in the following instructions.
  2. Click the “Download” button against the entry “Windows (x86, 32-bit), MySQL Installer MSI”. This would download the an exe file such as mysql-installercommunity-
  3. Double-click on the installer to start the installation.
  4. As you progress ahead after accepting the license terms and condition, you would find the interactive UI such as following. Choose the appropriate version of MySQL server and also, MySQL Workbench and click on Next. Figure 6: Selecting and installing MySQL Server and MySQL Workbench
  5. Clicking on Execute would install the MySQL server and MySQL workbench as shown in the following diagram: Figure 7: MySQL Server and Workbench installation in progress
  6. Once installation is complete, next few steps would require you to configure the MySQL database including setting root password, adding one or more users, opting to start MySQL server as a Windows service and so on. The quickest way will be to use default instructions as much as possible and finish the installation. Once all is done, you would see UI such as following: Figure 8: Completion of MySQL Server and Workbench installation
  7. Clicking on “Finish” button will take on the next window where you could choose to start MySQL workbench. Following is how the MySQL Workbench would look like after you click on MySQL server instance on the Workbench homepage, enter the root password and execute “Show databases” command: Figure 9: MySQL Workbench

Using MySQL Connector

Before testing MySQL database connection from Java program, one would need to add the MySQL JDBC connector library to the classpath. In this section, we will learn how to configure/add MySQL JDBC connector library to classpath while working with Eclipse IDE or command console.

The MySQL connector (Connector/J) comes in ZIP file (*.tar.gz). The MySQL connector is a concrete implementation of JDBC API. Once extracted, one can see a JAR file with name such as mysql-connector-java-xxx.jar. Following are different ways in which this JAR file is dealt with while working with or without IDEs such as Eclipse:

  1.  While working with Eclipse IDE, one can add the JAR file to the classpath by adding it as Library to the Build Path in project’s properties.
  2. While working with command console, one needs to specify the path to the JAR file in the -cp or -classpath argument when executing the Java application. Following is the sample command representing the preceding:
     java -cp .;/path/to/mysql-connector-java-xxx.jar com.healthapp.JavaClassName 

    Note the “.” in classpath (-cp) option. This is there to add the current directory to the classpath as well such that com.healthapp.JavaClassName can be located.

Connecting to MySQL Database from a Java Class

In this section, we will learn how to test the MySQL database connection from a Java program.

Before executing the code shown as follows in your Eclipse IDE, make sure to do the following:

  1.  Add the MySQL connector jar file by right-clicking on top-level project folder, clicking on “Properties”, clicking on “Java Build Path” and, then, adding mysqlconnector-java-xxx.jar file by clicking on “Add External JARs…”: Figure 10: Adding MySQL Java Connector to Java Build Path in Eclipse IDE
  2. Create a MySQL database namely “healthapp”. You could do that by accessing MySQL Workbench and executing the MySQL command such as “create database healthapp”. Following diagram represents the same: Figure 11: Creating new MySQL Database using MySQL Workbench
  3. Once done with the preceding steps, use the following code to test the connection to MySQL database from your Java class. On successful connection, you should be able to see “Database connected!” getting printed.
    import java.sql.Connection;
     import java.sql.DriverManager;
     import java.sql.SQLException;
     * Sample program to test MySQL database connection
     public class App
     public static void main( String[] args )
     String url =
     String username = "root";
     String password = "r00t"; //Root password set
     during MySQL installation procedure as
     described above.
     System.out.println("Connecting database...");
     try {
     Connection connection =
     DriverManager.getConnection(url, username,
     System.out.println("Database connected!");
     catch (SQLException e) {
     throw new IllegalStateException("Cannot
     connect the database!", e);

Introduction to Dockers

Docker is a virtualization technology which helps IT organizations achieve some of the following:

  1.  Enable Dev/QA team develop and test applications in a quick and easy manner in any environment.
  2. Break the barriers between Dev/QA and Operations teams during software development life cycle (SDLC) processes.
  3. Optimize infrastructure usage in the most appropriate manner.

In this section, we will emphasize on first point which would help us setup Spring web application development in quick and easy manner.

So far, we have seen traditional manners in which we could set up the Java web application development environment by installing different tools in independent manner and later configuring them appropriately. In a traditional setup, one would be required to setup and configure Java, Maven, Tomcat, MySQL server and so on, one tool at a time, by following manual steps. On the same lines, you could see that all of the steps described in preceding sections have to be performed one-by-one in manual fashion. Following are some of the disadvantages of setting up development/test environments in this manner:

  1.  Conflicting Runtimes: If a need arises to use software packages (say, different versions of Java and Tomcat) of different versions to run and test the same web application, it can become very cumbersome to manually set up the environment having different versions of software.
  2. Environments getting corrupted: If more than one developers are working in a particular development environment, there are chances that the environment could get corrupted due to changes made by one developer while others are not aware about. And, that generally leads to developers’/team’s productivity loss due to time spent in fixing the configuration issue or re-installing the development environment from scratch.
  3. “Works for me” syndrome: Have you come across another member of your team saying that the application works in their environment although the application seems to have broken?
  4. New Developers/Testers’ On-boarding: If there is a need to quickly on-board the new developers, manually setting up development environment takes some significant amount of time depending upon the applications’ complexity.

All of the praceding disadvantages could be taken care by making use of Dockers technology. In this section, we will learn briefly about some of the following:

  • What are Docker Containers?
  • What are key building blocks of Docker containers?
  • Installing Dockers Useful commands to work with Docker containers

What are Docker Containers?

In this section, we will try and understand what are Docker containers while comparing them with real-world containers. Simply speaking, Docker is an open platform for developing, shipping and running applications. It provides the ability to package and run an application in a loosely isolated environment called a container. Before going into details of Docker containers, let us try and understand the problems that are solved by real-world containers.

What are real-world containers good for?

Following picture represents real world containers which are used to package annything and everything and, then, transport the goods from one place to other in an easy and safe manner:Figure 12: Real-world containers

The following diagram represents different form of goods which needs to be transported using different from of transport mechanisms from one place to another: Figure 13: Different forms of goods vis-a-vis different form of transport mechanisms

The following diagram displays the matrix representing need to transport each of the goods via different transport mechanism. The challenge is to make sure that these goods get transported in easy and safe manner: Figure 14: Complexity associated with transporting goods of different types using different transport mechanisms

In order to solve preceding problem of transporting the goods in safe and easy manner irrespective of transport medium, the containers are used. Look at the following diagram: Figure 15: Goods can be packed within containers, and containers can be transported.

How does Docker containers relate to the real-world containers?

Now imagine the act of moving a software application from one environment to another environment starting from development right up to production. Following diagram represents complexity associated with making different application components work in different environments: Figure 16: Complexity associated with making different application components work in different environments

As per the preceding diagram, to make different application components work in different environments (different hardware platforms), one would require to make sure environment compatible software versions and related configurations are set appropriately. Doing this using manual steps can be real cumbersome and error prone task.

This is where docker containers fit in. Following diagram represents containerizing different application components using Docker containers. As like real-world containers, it would become very easy to move the containerized application components from one environment to another with very less or no issues: Figure 17: Docker containers to move application components across different environments

Docker containers

In simple terms, Docker containers provide an isolated and secured environment for the application components to run. The isolation and security allows one or many containers to run simultaneously on a given host. Often, for simplicity sake, Docker containers are loosely termed as lightweight-VMs (Virtual Machine). However, they are very much different from the traditional VMs. Docker containers do not need hypervisors to run as like virtual machines and, thus, multiple containers can be run on a given hardware combination.

Virtual machines include the application, the necessary binaries and libraries, and an entire guest operating system; all of which can amount to tens of GBs. On the other hand, Docker Containers include the application and all of its dependencies; but share the kernel with other containers, running as isolated processes in user space on the host operating system. Docker containers are not tied to any specific infrastructure: they run on any computer, on any infrastructure, and in any cloud. This very aspect make them look like a real-world container. Following diagram sums it all: Figure 18: Difference between traditional VMs and Docker containers

Following are some of the key building blocks of Docker technology:

  1. Docker Containers: Isolated and secured environment for applications to run.
  2. Docker engine: A client-server application having following components: Daemon process used to create and manage Docker objects, such as images, containers, networks, and data volumes. A REST API interface and A command line interface (CLI) client
  3. Docker client: Client program that invokes Docker engine using APIs.
  4. Docker host: Underlying operating system sharing the kernel space with Docker containers. Until recently, Windows OS needed Linux virtualization to host Docker containers. 
  5. Docker hub: Public repository used to manage Docker images posted by various users. Images made public are available for all to download in order to create containers using those images.

What are key building blocks of Dockers containers?

For setting up our development environment, we will rely on Docker containers and assemble them together using the tool called as Docker compose which we shall learn about little later. Let us understand some of the following which can also be termed as key building blocks of Docker containers:

  1.  Docker image: In simple terms, Docker image can be thought of as a “class” in Java. Docker containers can be thought of as running instances of the image as like having one or more “instances” of a Java class. Technically speaking, Docker images consist of a list of layers that are stacked on top of each other to form a base for containers’ root file system. Following diagram represents command which can be used to create a Docker container using an image named helloworld: Figure 19: Docker command representing creation of Docker container using a Docker image. In order to set up our development environment, we will require images of following to create the respective Docker containers: – Tomcat – MySQL.
  2. Dockerfile: Dockerfile is a text document that contains all the commands which could be called on the command line to assemble or build an image. docker build command is used to build an image from a Dockerfile and a context. In order to create custom images for Tomcat and MySQL, it may be required to create a Dockerfile and, then, build the image. Following is a sample command for building an image using a Dockerfile:
    docker build -f tomcat.df -t tomcat_debug 

The preceding command would look for the Dockerfile “tomcat.df” in the current directory specified by “.” and build the image with tag, “tomcat_debug”.

Installing Dockers

Now that we have got an understanding on What are Dockers, lets install Dockers. We shall look into steps that are required to install Dockers on Windows OS:

  1.  Download the Windows version of Docker Toolbox from the webpage, https https://www.docker.com/products/docker-toolbox.
  2. Docker toolbox comes as an installer which can be double-clicked for quick setup and launch of the docker environment. Following comes with Docker toolbox installation:
  • Docker Machine for running docker-machine commands.
  • Docker Engine for running the docker commands.
  • Docker Compose for running the docker-compose commands. This is what we are looking for.
  • Kitematic, the Docker GUI.
  • A shell preconfigured for a Docker command-line environment.
  • Oracle VirtualBox.

Setting up Development Environment using Docker Compose

In this section, we will learn how to setup on-demand, self-service development environment using Docker compose. Following are some of the points covered in this section:

  • What is Docker compose?
  • Docker compose script for setting up the development environment

What is Docker Compose?

Docker compose is a tool for defining and running multi-container Docker applications. One will require to create a Compose file to configure the application’s services. Following steps are required to be taken in order to work with Docker compose:

  • Define the application’s environment with a Dockerfile so it can be reproduced anywhere.
  • Define the services that make up the application in docker-compose.yml so they can be run together in an isolated environment.
  • Lastly, run docker-compose up and Compose will start and run the entire application.

As we are going to setup a multi-container applications using Tomcat and MySQL as different containers, we will use Docker compose to configure both of them and, then, assemble the application.

Docker Compose script for setting up the development environment

In order to come up with a Docker compose script which can set up our Spring Web App development environment with one script execution, we will first set up images for following by creating independent Dockerfiles.

  • Tomcat 8.x with Java and Maven installed as one container
  • MySQL as another container

Setting up Tomcat 8.x as a Container Service

Following steps can be used to setup Tomcat 8.x along with Java 8 and Maven 3.x as one container:

  1. Create a folder and put following files within the folder. The source code for the files will be given as follows:
    • tomcat.df
    • create_tomcat_admin_user.sh
    • run.sh
  2. Copy following source code for tomcat.df:
    FROM phusion/baseimage:0.9.17
    RUN echo "deb http://archive.ubuntu.com/ubuntu trusty main
    universe" > /etc/apt/sources.list
    RUN apt-get -y update
    RUN DEBIAN_FRONTEND=noninteractive apt-get install -y -q pythonsoftware-properties
    ENV JAVA_HOME /usr/lib/jvm/java-8-oracle
    RUN echo 'deb http://ppa.launchpad.net/webupd8team/java/ubuntu
    trusty main' >> /etc/apt/sources.list && 
     echo 'deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu
    trusty main' >> /etc/apt/sources.list && 
     apt-key adv --keyserver keyserver.ubuntu.com --recv-keys
    C2518248EEA14886 && 
     apt-get update && 
     echo oracle-java${JAVA_VER}-installer shared/accepted-oraclelicense-v1-1
    select true | sudo /usr/bin/debconf-set-selections &&
     apt-get install -y --force-yes --no-install-recommends oraclejava${JAVA_VER}-installer
    oracle-java${JAVA_VER}-set-default && 
     apt-get clean && 
     rm -rf /var/cache/oracle-jdk${JAVA_VER}-installer
    RUN update-java-alternatives -s java-8-oracle
    RUN echo "export JAVA_HOME=/usr/lib/jvm/java-8-oracle" >> ~/.bashrc
    RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
    RUN mkdir -p /usr/share/maven 
     && curl -fsSL
     | tar -xzC /usr/share/maven --strip-components=1 
     && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn
    ENV MAVEN_HOME /usr/share/maven
    VOLUME /root/.m2
    RUN apt-get update && 
     apt-get install -yq --no-install-recommends wget pwgen cacertificates
     apt-get clean && 
     rm -rf /var/lib/apt/lists/*
    RUN wget -q
     wget -qOhttps://archive.apache.org/dist/tomcat/tomcat-${TOMCAT_MAJOR_VERSIO
    | md5sum
    -c - && 
     tar zxf apache-tomcat-*.tar.gz && 
     rm apache-tomcat-*.tar.gz && 
     mv apache-tomcat* tomcat
    ADD create_tomcat_admin_user.sh /create_tomcat_admin_user.sh
    RUN mkdir /etc/service/tomcat
    ADD run.sh /etc/service/tomcat/run
    RUN chmod +x /*.sh
    RUN chmod +x /etc/service/tomcat/run
    EXPOSE 8080
    CMD ["/sbin/my_init"]
  3. Copy following code in a file named as create_tomcat_admin_user.sh. This file should be created in the same folder as preceding file, tomcat.df. While copying into notepad and later using with docker terminal, you may find Ctrl-M character inserted at the end of the line. Make sure that those lines are appropriately handled and removed:
    if [ -f /.tomcat_admin_created ]; then
     echo "Tomcat 'admin' user already created"
     exit 0
    PASS=${TOMCAT_PASS:-$(pwgen -s 12 1)}
    _word=$( [ ${TOMCAT_PASS} ] && echo "preset" || echo "random" )
    echo "=> Creating an admin user with a ${_word} password in Tomcat"
    sed -i -r 's/</tomcat-users>//' ${CATALINA_HOME}/conf/tomcatusers.xml
    echo '<role rolename="manager-gui"/>' >>
    echo '<role rolename="manager-script"/>' >>
    echo '<role rolename="manager-jmx"/>' >>
    echo '<role rolename="admin-gui"/>' >>
    echo '<role rolename="admin-script"/>' >>
    echo "<user username="admin" password="${PASS}" roles="managergui,manager-script,manager-jmx,admin-gui,
    admin-script"/>" >>
    echo '</tomcat-users>' >> ${CATALINA_HOME}/conf/tomcat-users.xml
    echo "=> Done!"
    touch /.tomcat_admin_created
    echo "You can now configure to this Tomcat server using:"
    echo ""
    echo " admin:${PASS}"
    echo ""
  4. Copy following code in a file named as run.sh in the same folder as preceding two files:
    if [ ! -f /.tomcat_admin_created ]; then
    exec ${CATALINA_HOME}/bin/catalina.sh run
  5. Open up a Docker terminal and go to folder where these files are located.
  6. Execute following command to create the Tomcat image. In few minutes, the tomcat image will be created:
    docker build -f tomcat.df -t demo/tomcat:8 .
  7. Execute the command such as following and make sure that an image with name as demo/tomcat is found:
    docker images
  8. Next, run a container with name such as “tomcatdev” using following command:
    docker run -ti -d -p 8080:8080 --name tomcatdev -v "$PWD":/mnt/
  9. Open a browser and type the URL as You should be able to see following page getting loaded. Note the URL and the Tomcat version, 8.5.8. This is the same version we earlier installed (check figure 1.4): Figure 20: Tomcat 8.5.8 installed as a Docker container
  10. You could access the container through the terminal using command with following command. Make sure to check the Tomcat installation inside folder “/tomcat”. Also, execute command such as “java -version” and “mvn -v” to check the version of Java and Maven respectively:
    docker exec -ti tomcatdev /bin/bash

In this section, we learnt to setup Tomcat 8.5.8 along with Java 8 and Maven 3.x as one container.

Setting up MySQL as a Container Service

In this section, we will learn how to setup MySQL as a container service. In the docker terminal, execute the following command:

docker run -ti -d -p 3326:3306 --name mysqldev -e MYSQL_ROOT_PASSWORD=r00t -v "$PWD":/mnt/ mysql:5.7

The preceding command setup MySQL 5.7 version within the container and starts the mysqld service. Open MySQL Workbench and create a new connection by entering the details such as following and click “Test Connection”. You should be able to establish the connection successfully: Figure 21: MySQL server running in the container and accessible from host machine at 3326 port using MySQL Workbench

Docker Compose script to setup the Dev Environment

Now, that we have setup both Tomcat and MySQL as individual containers, let us learn to create a Docker compose script using which both the containers can be started simultaneously thereby starting the Dev environment.

  1.  Save following source code as docker-compose.yml in the same folder as preceding mentioned files:
    version: '2'
     context: .
     dockerfile: tomcat.df
     - "8080:8080"
     - .:/mnt/
     - db
     image: mysql:5.7
     - "3326:3306"
  2. Execute following command to start and stop the services:
    // For starting the services in the foreground
    docker-compose up
    // For starting the services in the background (detached mode)
    docker-compose up -d
    // For stopping the services
    docker-compose stop
  3. Test whether both the default Tomcat web app and MySQL server can be accessed. Access the URL, and make sure that the web page as shown in figure 1.20 is displayed. Also, open MySQL Workbench and access the MySQL server at IP, and port 3326 (as specified in the preceding docker-compose.yml file).


In this article, we learnt how we could start and stop the Web app Dev environment on- demand. Note that with these scripts including Dockerfiles, shell scripts and Dockercompose file, you could setup the Dev environment on any machine where Docker Toolbox could be installed.

Resources for Article:


Further resources on this subject:


Please enter your comment!
Please enter your name here