Is it a good practice to deploy multiple microservices in a single tomcat container

Upasana | May 27, 2019 | 1 min read | 1,308 views


As stated in 12 factor app, we should deploy each microservice in a separate process to allow independent scaling. Therefore, it is best to run each microservice in its own servlet container (Tomcat, Jetty, Undertow, etc.). Spring boot provides support for easily embedding container inside the executable jar, so you just need to run the jar and service is up and running in desired container.

Creating a boot jar using build.gradle
springBoot {
    buildInfo()
}

bootJar {
    archiveBaseName = 'shunya-app'
    version = version
    launchScript()
    mainClassName = "com.shunya.App"
}

Define port as 0 in config file will make your application take a random port. The actual server port can be captured inside a variable using ${local.server.port}

In real cloud environment, Eureka client discovery can be used to locate the host and port number dynamically, thereby eliminating the need for knowing the host and port in advance.

Spring Boot provides us with options to use Tomcat, Jetty or Undertow servlet container in embedded mode with just few lines of code in build.gradle file.

build.gradle - switching from tomcat to undertow
dependencies {
	compile('org.springframework.boot:spring-boot-starter-web') {
		exclude module: "spring-boot-starter-tomcat"    (1)
	}
	compile("org.springframework.boot:spring-boot-starter-undertow")
	//...other dependencies
}
1 In above example we have excluded the default tomcat and opted for undertow as the embedded servlet container for Spring Boot Application.

Top articles in this category:
  1. 50 microservices interview questions for Java developers
  2. Cracking Spring Microservices Interviews - question bank
  3. How will you Partition a typical e-shop into Microservices Architecture
  4. Why Microservices are better than Monoliths
  5. What is Spring Boot and what are its advantages
  6. Spring Cloud and its advantages

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.