Keeping your cloud environment clean is vital for performance and security. If you no longer need Apache Tomcat on your Amazon EC2 instance, removing it properly is essential. This guide will show you how to use the Yum package manager to cleanly uninstall Tomcat in just a few steps.
Step 1: Connect to Your EC2 Instance
Use your favorite SSH client to log into your Amazon EC2 Linux instance. Before making changes, it's always a good idea to check if the Tomcat service is currently running.
Step 2: Stop the Tomcat Service
You should never uninstall a service while it's active. Use the command sudo systemctl stop tomcat (or your specific service name) to safely shut down the server before proceeding with the removal.
Step 3: Uninstall Using Yum
The Yum package manager makes removal very easy. Run sudo yum remove tomcat. Yum will calculate the dependencies and ask for your confirmation. Type 'y' to proceed, and it will remove the core binaries from your system.
Step 4: Clean Up Remaining Files
Sometimes configuration files or web applications stay behind. Check directories like /var/lib/tomcat or /etc/tomcat to manually remove any leftover folders if you want a completely fresh start.
Step 5: Verify the Removal
To confirm Tomcat is gone, try checking the version or status again. If the system reports that the command or service is not found, you have successfully cleaned your EC2 instance!
Deploying a Java application to the cloud is a major milestone for any developer. Apache Tomcat is the industry-standard web server for Java, and hosting it on an Amazon EC2 instance gives you incredible scale and control. This guide walks you through the entire process, from installation to deploying your first WAR file.
Step 1: Install Tomcat Using Yum
Using the Yum package manager is the fastest way to get Tomcat running on Amazon Linux. Connect to your EC2 instance via SSH and run the install command. This ensures all the necessary dependencies are handled automatically by the system.
Step 2: Configure Tomcat Users
To access the Tomcat Manager GUI, you need to set up user permissions. Navigate to the tomcat-users.xml file and add roles like "manager-gui" and "admin-gui." This allows you to upload and manage your web applications directly through your browser.
Step 3: Allow Remote Access
By default, Tomcat's Manager app is restricted to localhost. You'll need to modify the context.xml file within the Manager app folder to allow traffic from your specific IP address. Don't forget to also open Port 8080 in your AWS Security Group!
Step 4: Deploy Your WAR File
The "moment of truth" is deploying your application. You can either upload your .war file through the Tomcat Manager Dashboard or manually move it into the webapps directory on your server. Tomcat will automatically extract and start your application.
Step 5: Verify Your Deployment
Open your browser and enter your EC2 public IP followed by :8080/your-app-name. If everything is set up correctly, you should see your Java application live on the internet! Congratulations on your cloud deployment!
Deploying a web application can seem scary, but it’s actually a very logical process. In this guide, we will walk through how to take your Java Web Service, package it into a WAR file, and get it running on a professional server like Apache Tomcat hosted on Amazon EC2.
Step 1: Generating the WAR File
A WAR (Web Application Archive) file is like a package that contains everything your web app needs to run. Using your favorite IDE (like Eclipse or IntelliJ) or Maven, you generate this file so it can be "dropped" into a server.
Step 2: Setting Up Amazon EC2
Amazon EC2 provides a virtual computer in the cloud. For this setup, we use a Linux-based instance. You'll need to:
Launch an EC2 instance.
Configure Security Groups to allow traffic on Port 8080 (where Tomcat lives).
Connect to your instance via SSH.
Step 3: Installing Apache Tomcat
Apache Tomcat is the engine that actually "runs" your Java code. We install Tomcat on the EC2 instance, making sure Java is also installed. Once Tomcat is running, you can access its management page through your EC2 instance's IP address.
Step 4: Deployment and Verification
Finally, we upload our WAR file to the Tomcat webapps folder. Tomcat automatically detects it and starts the application. You can then test your Web Service using the public DNS of your AWS instance!
Watch More from Ram N Java
Check out these other helpful videos to grow your skills:
While Spring Boot's embedded server is great for development, many enterprise environments require deploying to an external Tomcat instance. This process gives you more control over the server environment and configuration. In this guide, we'll demystify the "WAR file magic" needed to get your application running on a standalone server.
Step 1: Modify your Build Configuration
The first step is changing your packaging from JAR to WAR in your pom.xml or build.gradle file. You also need to mark the embedded Tomcat dependency as "provided" so it doesn't conflict with the external server you'll be using.
Step 2: Update the Main Application Class
To run as a WAR, your main class needs to extend SpringBootServletInitializer and override the configure method. This tells the external Tomcat server how to launch your Spring Boot application correctly.
Step 3: Generate the WAR File
Run your build command (like mvn clean package). Navigate to your target folder, and you'll find your brand new WAR file. This single file contains everything your application needs to run on the server.
Step 4: Installation & Deployment
Ensure your external Tomcat is installed and running. Simply move your WAR file into the Tomcat webapps directory. Tomcat will detect the new file, automatically extract it, and start your application within seconds.
Step 5: Access Your Application
Open your browser and navigate to localhost:8080/your-war-filename. If everything was done correctly, your Spring Boot application is now live on an external server! This is a major step toward production-ready deployment.
Mastering Spring Boot Deployment on External Tomcat
Transitioning from Spring Boot's embedded server to an external Tomcat instance is a common requirement for production-grade REST APIs. While embedded servers are great for speed, external servers offer centralized management and shared resources. This guide makes the switch simple and efficient.
Step 1: Packaging as a WAR File
To deploy to an external server, you must change your build packaging. In your pom.xml, update the <packaging> tag to war. This ensures Maven creates the correct file structure for Tomcat to read.
Step 2: Configure the Servlet Initializer
Your Spring Boot application needs a starting point that an external container can recognize. You’ll need to extend the SpringBootServletInitializer class in your main entry point. This small code adjustment bridges the gap between your app and the Tomcat server.
Step 3: Excluding Embedded Tomcat
To avoid version conflicts, mark the spring-boot-starter-tomcat dependency as provided in your dependencies. This tells the build process not to include the server inside your WAR file, as the external Tomcat will already provide it.
Step 4: The Deployment Process
Once your WAR file is generated, copy it into the webapps directory of your standalone Tomcat installation. Tomcat will automatically detect the file, extract it, and deploy your REST endpoints in seconds.
Step 5: Testing Your REST Endpoints
Access your API by appending the WAR filename to your server URL, for example: http://localhost:8080/my-api-name/hello. If you see your REST response, your deployment was a success! You are now running Spring Boot like a pro.
Apache Tomcat 9 is a powerful, open-source web server used by millions of developers to host Java-based web applications. While it might seem technical, installing it on Windows is actually quite simple when you follow the right steps. This guide will get your local server up and running in no time.
Step 1: Verify Java Installation
Before you even download Tomcat, you must have the Java Development Kit (JDK) installed on your Windows machine. Tomcat is written in Java and requires it to run. Open your Command Prompt and type java -version to make sure you're ready to go.
Step 2: Download the Tomcat 9 Installer
Head over to the official Apache Tomcat 9 download page. For Windows users, the easiest option is the "32-bit/64-bit Windows Service Installer" (the .exe file). This installer handles most of the configuration for you automatically.
Step 3: Run the Setup Wizard
Launch the downloaded installer and follow the prompts. During setup, you can choose which components to install (like the Manager GUI). You'll also be asked to specify the port—the default is usually 8080. Keep this in mind for later!
Step 4: Configure the Java Path
The installer will ask for the location of your JRE or JDK. It usually finds this automatically, but double-check that it points to the correct folder (e.g., C:\Program Files\Java\jdk-11) so Tomcat can launch without errors.
Step 5: Start and Test Your Server
Once the installation is complete, you can start the Tomcat service. Open your browser and go to http://localhost:8080. If you see the famous Tomcat "If you're seeing this, you've successfully installed Tomcat" page, congratulations! You're ready to deploy your apps.
By default, a Spring Boot application serves content from the root context path ("/"). However, in many real-world scenarios—especially when hosting multiple applications on a single domain—you need to define a custom context path. While many developers use property files, understanding how to do this programmatically gives you much more flexibility.
The Problem: Why Change the Context Path?
When your API grows, you might want to version it (e.g., /api/v1) or distinguish it from other services on the same server. Changing the context path ensures that your application only responds to requests starting with your specified prefix, preventing URL collisions.
Enter TomcatServletWebServerFactory
One of the most powerful ways to customize the embedded Tomcat server is through the TomcatServletWebServerFactory bean. By overriding this factory, you can programmatically inject configuration settings—including the context path—directly into the web server component during startup.
Step-by-Step Implementation
To implement this, you simply create a configuration class and define a WebServerFactoryCustomizer bean. Inside this bean, you can use the setContextPath() method to specify exactly where your application should live. This method is incredibly useful for dynamic configurations that might change based on environment variables.
The Property File Alternative
For simpler use cases, you can also use the server.servlet.context-path property in your application.properties or application.yml file. While less flexible than the programmatic approach, it is a quick and efficient way to handle static context path changes.
Testing Your Changes
After applying the change, restart your application. You'll notice that the root URL no longer works. You must now append your new context path to the URL (e.g., http://localhost:8080/my-app/). Your endpoints are now organized and ready for professional deployment!
In high-traffic Java web applications, opening and closing physical database connections repeatedly creates massive performance overhead.
C3P0 is an open-source JDBC connection pool library that pre-initializes a pool of reusable connections. When your servlet requires database access, it simply borrows a connection from the pool and returns it when finished, significantly improving response times.
Step 1: Add Required JAR Files to Tomcat
To enable Tomcat and your application to use C3P0 with Oracle Database, copy the following JAR files directly into your Tomcat server's lib folder:
C3P0 JARs: Download the C3P0 library and place c3p0.jar and mchange-commons-java.jar into Tomcat/lib.
Oracle JDBC Driver: Add ojdbc6.jar (or compatible driver) into Tomcat/lib so Tomcat can communicate with Oracle.
Step 2: Configure the C3P0 DataSource in context.xml
Define the connection pool resource inside Apache Tomcat's context.xml file so it registers with the JNDI naming service:
Declare the resource reference inside your web application's web.xml deployment descriptor:
<resource-ref>
<description>Oracle DB Connection</description>
<res-ref-name>jdbc/hrDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Step 4: Retrieve and Use Connections in the Servlet
Inside your Servlet's init() method, perform a JNDI lookup to obtain the DataSource. Then, inside doGet(), retrieve a connection from the pool, execute SQL queries, and return output to the client:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class EmployeeInfoServlet extends HttpServlet
{
private static final long serialVersionUID =1L;
DataSource dataSource =null;
public void init( ServletConfig config )
{
try
{
System.out
.println("-----------------------------------------------------");
System.out
.println("init method has been called and servlet is initialized");
/*
* Using JDNI lookup get the DataSource.
*/
Context initContext =new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/HRDB");
System.out.println("Using JDNI lookup got the DataSource : "+ dataSource);
System.out
.println("-----------------------------------------------------");
}
catch( Exception exe )
{
exe.printStackTrace();
}
}
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
System.out
.println("-----------------------------------------------------");
System.out.println("doGet method has been called");
System.out
.println("-----------------------------------------------------");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title ="Employee Information From Oracle Database";
out.print("<html><body bgcolor=\"#f0f0f0\">");
out.print("<h1 align=\"center\">"+ title +"</h1>\n");
showEmployeeInformation(out);
out.print("</body></html>");
}
public void destroy()
{
System.out
.println("-----------------------------------------------------");
System.out
.println("destroy method has been called and servlet is destroyed");
System.out
.println("-----------------------------------------------------");
}
private void showEmployeeInformation( PrintWriter out )
{
Connection connection =null;
Statement stmt =null;
try
{
/*
* Get connection from the DataSource
*/
connection = dataSource.getConnection();
/*
* Execute the Query
*/
stmt = connection.createStatement();
String sql ="select employee_id,first_name,last_name,email,phone_number from employees";
ResultSet rs = stmt.executeQuery(sql);
/*
* Iterate the ResultSet and get each row Information.
*/while( rs.next() )
{
/*
* Retrieve by column name
*/
int id = rs.getInt("employee_id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String email = rs.getString("email");
String phoneNumber = rs.getString("phone_number");
/*
* Display values
*/
out.print("employee_id: "+ id+"<br>");
out.print("first_name: "+ firstName+"<br>");
out.print("last_name: "+ lastName+"<br>");
out.print("email: "+ email+"<br>");
out.println("phone_number: "+ phoneNumber+"<br>");
out.println("-------------------------------------------");
}
rs.close();
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
/*
* finally block used to close resources
*/try
{
if( stmt !=null )
{
stmt.close();
}
}
catch( SQLException sqlException )
{
sqlException.printStackTrace();
}
try
{
if( connection !=null )
{
connection.close();
}
}
catch( SQLException sqlException )
{
sqlException.printStackTrace();
}
}
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?><web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true"version="3.0"><display-name>EmployeeInfoDemo</display-name><description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
</description><servlet><servlet-name>employeeInfoServlet</servlet-name><servlet-class>EmployeeInfoServlet</servlet-class></servlet><servlet-mapping><servlet-name>employeeInfoServlet</servlet-name><url-pattern>/employeeInfo</url-pattern></servlet-mapping><resource-ref><description>DB Connection</description><res-ref-name>jdbc/HRDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth></resource-ref></web-app>
Creating database connections on every user request leads to high latency and heavy memory usage.
C3P0 solves this problem by maintaining a pool of pre-established database connections. Instead of opening a brand-new connection each time, your Java Servlet borrows an existing connection from the pool, runs the SQL queries, and releases it back to the pool immediately.
Step 1: Add Required Libraries to Tomcat
Make sure the following JAR files are placed inside the Apache Tomcat/lib folder:
c3p0.jar & mchange-commons-java.jar: The core C3P0 connection pooling binaries.
mysql-connector-java.jar: The MySQL JDBC driver to allow Tomcat to communicate with your MySQL server.
Step 2: Configure C3P0 DataSource in context.xml
Define the MySQL connection pool resource inside your Tomcat configuration (META-INF/context.xml or conf/context.xml):
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
JDBC|Servlets : Tomcat C3PO Connection Pooling - Mysql
CityInfoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class CityInfoServlet extends HttpServlet
{
private static final long serialVersionUID =1L;
DataSource dataSource =null;
public void init( ServletConfig config )
{
try
{
System.out
.println("-----------------------------------------------------");
System.out
.println("init method has been called and servlet is initialized");
/*
* Using JDNI lookup get the DataSource.
*/
Context initContext =new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/worldDB");
System.out.println("Using JDNI lookup got the DataSource : "+ dataSource);
System.out
.println("-----------------------------------------------------");
}
catch( Exception exe )
{
exe.printStackTrace();
}
}
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
System.out
.println("-----------------------------------------------------");
System.out.println("doGet method has been called");
System.out
.println("-----------------------------------------------------");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title ="City Information From Mysql Database";
out.print("<html><body bgcolor=\"#f0f0f0\">");
out.print("<h1 align=\"center\">"+ title +"</h1>\n");
showCityInformation(out);
out.print("</body></html>");
}
public void destroy()
{
System.out
.println("-----------------------------------------------------");
System.out
.println("destroy method has been called and servlet is destroyed");
System.out
.println("-----------------------------------------------------");
}
private void showCityInformation( PrintWriter out )
{
Connection connection =null;
PreparedStatement preparedStatement =null;
try
{
String sql ="select * from city limit ?";
/*
* Get connection from the DataSource
*/
connection = dataSource.getConnection();
/*
* Execute the query
*/
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 10);
ResultSet rs = preparedStatement.executeQuery();
while( rs.next() )
{
int id = rs.getInt(1);
String name = rs.getString(2);
String countryCode = rs.getString(3);
String district = rs.getString(4);
int population = rs.getInt(5);
/*
* Display values
*/
out.print("ID: "+ id +"<br>");
out.print("Name: "+ name+"<br>");
out.print("CountryCode: "+ countryCode+"<br>");
out.print("District: "+ district+"<br>");
out.println("Population: "+ population+"<br>");
out.println("--------------------------------------"+"<br>");
}
rs.close();
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
/*
* finally block used to close resources
*/try
{
if( preparedStatement !=null )
{
preparedStatement.close();
}
}
catch( SQLException sqlException )
{
sqlException.printStackTrace();
}
try
{
if( connection !=null )
{
connection.close();
}
}
catch( SQLException sqlException )
{
sqlException.printStackTrace();
}
}
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?><web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true"version="3.0"><display-name>City Info Demo</display-name><description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
</description><servlet><servlet-name>cityInfoServlet</servlet-name><servlet-class>CityInfoServlet</servlet-class></servlet><servlet-mapping><servlet-name>cityInfoServlet</servlet-name><url-pattern>/cityInfo</url-pattern></servlet-mapping><resource-ref><description>DB Connection</description><res-ref-name>jdbc/worldDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth></resource-ref></web-app>
index.html
<!DOCTYPE HTML><htmllang="en"><head><metacharset="UTF-8"><title>City Information</title></head><body><p><h3>Show City Information</H3><p></p><ul><li><ahref="cityInfo">Show City Information</a></li></ul></body></html>
To Download CityInfoDemoTomcatC3POMysqlApp Project Click the below link