Java WAR Deployment

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 286 of 306

Java WAR deployment means installing a .war file into a servlet container such as Apache Tomcat so the container runs your web application. Unlike an executable JAR, a WAR has no main method: Tomcat starts it, gives it a URL path and manages its life. You use WAR deployment when your app is built on Servlets, JSP or Jakarta EE, or when your company already runs a shared Tomcat server.

This lesson installs Tomcat 11 on a Linux server, deploys the student-portal.war built in Build WAR File in Java in three different ways, tunes the JVM, and ends with a scripted release that rolls back automatically. All commands were run on Ubuntu with JDK 21 and Tomcat 11.0.


What a Java WAR Deployment Needs

PieceExamplePurpose
WAR filestudent-portal.warYour compiled web application
Java runtimeOpenJDK 21Runs Tomcat (Tomcat 11 needs Java 17+)
Servlet containerApache Tomcat 11 in /opt/tomcatLoads WARs and serves HTTP
Dedicated usertomcatTomcat does not run as root
setenv.sh/opt/tomcat/bin/setenv.shJVM memory and app settings

Tomcat Folder Layout

FolderContains
bin/Start/stop scripts (catalina.sh, startup.sh, version.sh)
conf/Server settings (server.xml, tomcat-users.xml, context files)
webapps/Deployed applications (WARs and their unpacked folders)
logs/catalina.out, access logs, app logs
lib/JARs shared by all apps, including the Servlet API
work/, temp/Compiled JSPs and temporary files

How it works:

  • Tomcat is the "server" part; your WAR only contains your own classes and libraries. That is why the Servlet API is provided scope when you build the WAR.
  • One Tomcat can run many WARs side by side, each with its own URL path and class loader.

Install Tomcat 11 on Linux

Tomcat is a plain archive: download it, unpack it and give it to a system user.

# on the server
sudo apt update
sudo apt install -y openjdk-21-jre-headless

TOMCAT_VERSION=11.0.27   # check tomcat.apache.org for the newest 11.0.x
cd /tmp
curl -fsSLO "https://archive.apache.org/dist/tomcat/tomcat-11/v${TOMCAT_VERSION}/bin/apache-tomcat-${TOMCAT_VERSION}.tar.gz"

sudo useradd --system --create-home --home-dir /opt/tomcat --shell /usr/sbin/nologin tomcat
sudo tar -xzf "apache-tomcat-${TOMCAT_VERSION}.tar.gz" -C /opt/tomcat --strip-components=1
sudo chown -R tomcat:tomcat /opt/tomcat
sudo -u tomcat /opt/tomcat/bin/version.sh | grep -E "Server version|JVM Version"
Server version: Apache Tomcat/11.0.27
JVM Version:    21.0.12+7-Ubuntu-1ubuntu224.04

How it works:

  • --strip-components=1 drops the top apache-tomcat-11.0.27/ folder, so bin, conf and webapps land directly in /opt/tomcat.
  • The tomcat user owns every file. If someone breaks into the app, they get only this user's rights.
  • archive.apache.org keeps every release, so the same command works for any version number.

Note: Always use the latest 11.0.x patch release. Tomcat publishes security fixes almost every month, and only the newest patch in a branch has all of them.


Set JVM Options With setenv.sh

Never edit catalina.sh. Tomcat reads your settings from bin/setenv.sh if the file exists.

# /opt/tomcat/bin/setenv.sh
JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
CATALINA_PID="$CATALINA_BASE/temp/tomcat.pid"
CATALINA_OPTS="-Xms256m -Xmx512m -XX:+ExitOnOutOfMemoryError -Duser.timezone=Asia/Kolkata"
# settings your web app reads with System.getenv(...)
export APP_ENV=prod
sudo chown tomcat:tomcat /opt/tomcat/bin/setenv.sh
sudo -u tomcat /opt/tomcat/bin/startup.sh
ps -o args= -p "$(cat /opt/tomcat/temp/tomcat.pid)" | tr ' ' '\n' | grep -E "^-X|^-Duser"
Tomcat started.
-Xms256m
-Xmx512m
-XX:+ExitOnOutOfMemoryError
-Duser.timezone=Asia/Kolkata

How it works:

  • CATALINA_OPTS is applied only when Tomcat starts, not when you run shutdown.sh. Put heap and app settings here.
  • JAVA_OPTS also exists, but it is used for start and stop commands, so a large -Xmx there wastes memory every time you stop Tomcat.
  • CATALINA_PID makes the scripts write a PID file, which the ps command uses to show the real JVM arguments.

Deploy a WAR by Copying It to webapps

The simplest Java WAR deployment is a file copy. Tomcat watches webapps/ and deploys anything new.

# on your machine
scp target/student-portal.war asha@203.0.113.10:/tmp/
# on the server
sudo install -o tomcat -g tomcat -m 640 /tmp/student-portal.war /opt/tomcat/webapps/
sleep 3
grep "student-portal" /opt/tomcat/logs/catalina.out | tail -n 2
curl -s "http://localhost:8080/student-portal/hello?name=Asha"
INFO [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [/opt/tomcat/webapps/student-portal.war]
INFO [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/opt/tomcat/webapps/student-portal.war] has finished in [298] ms
Hello, Asha!

How it works:

  • install -o tomcat -g tomcat copies the file and sets the owner in one step. A WAR owned by root may fail to unpack.
  • Tomcat's autoDeploy check runs every few seconds. It unpacks the WAR into webapps/student-portal/ and starts it.
  • The file name decides the URL: student-portal.war is served at /student-portal.

Redeploy and Undeploy

# redeploy: copy a newer WAR over the old one
sudo install -o tomcat -g tomcat -m 640 /tmp/student-portal.war /opt/tomcat/webapps/

# undeploy: delete the WAR, Tomcat removes the unpacked folder too
sudo rm /opt/tomcat/webapps/student-portal.war
sleep 3
ls /opt/tomcat/webapps
ROOT  docs  examples  host-manager  manager

How it works:

  • When Tomcat sees a newer WAR timestamp, it stops the old app, deletes the unpacked folder and deploys again.
  • Deleting the WAR undeploys the app. Never delete only the unpacked folder while the WAR is still there; Tomcat would simply unpack it again.

Note: On a production server, delete the sample apps (docs, examples, host-manager) so they cannot be used to learn about your server. Keep manager only if you use it, as shown below.


Serve the App at the Root URL

To serve an app at http://server:8080/ instead of /student-portal, deploy it as ROOT.war.

sudo rm -rf /opt/tomcat/webapps/ROOT
sudo install -o tomcat -g tomcat -m 640 /tmp/student-portal.war /opt/tomcat/webapps/ROOT.war
sleep 3
curl -s "http://localhost:8080/hello?name=Ravi"
Hello, Ravi!
WAR name in webapps/URL path
student-portal.war/student-portal
ROOT.war/
api#v2.war/api/v2
student-portal##003.war/student-portal (version 003)

How it works:

  • ROOT is a reserved name for the empty context path. The default Tomcat welcome page lives in webapps/ROOT, so remove it first.
  • In real setups a reverse proxy such as Nginx usually sits in front of Tomcat on port 443 and forwards requests to port 8080.

Deploy a WAR From Outside webapps With a Context File

Copying into webapps mixes your releases with Tomcat's own files. A context file tells Tomcat to load a WAR from any folder, which suits the versioned release folders used in Java JAR Deployment.

sudo -u tomcat mkdir -p /opt/apps/student-portal/releases/1.0.0
sudo install -o tomcat -g tomcat -m 640 /tmp/student-portal.war \
     /opt/apps/student-portal/releases/1.0.0/app.war
<!-- /opt/tomcat/conf/Catalina/localhost/student-portal.xml -->
<Context docBase="/opt/apps/student-portal/releases/1.0.0/app.war">
    <!-- value an app can read with JNDI or ServletContext -->
    <Parameter name="supportEmail" value="help@gocourse.example" override="false"/>
</Context>
sudo chown tomcat:tomcat /opt/tomcat/conf/Catalina/localhost/student-portal.xml
sleep 3
curl -s "http://localhost:8080/student-portal/hello?name=Meena"
Hello, Meena!

How it works:

  • The file name student-portal.xml sets the context path /student-portal. docBase points at the WAR anywhere on disk.
  • Switching versions means editing one line (docBase). Tomcat notices the changed file and redeploys.
  • <Parameter> values are read in a servlet with getServletContext().getInitParameter("supportEmail"), so each server can have different settings without rebuilding the WAR.

Deploy With the Tomcat Manager API

The Manager app has a plain-text API that build tools and scripts can call over HTTP. First create a user with the manager-script role.

<!-- /opt/tomcat/conf/tomcat-users.xml (inside <tomcat-users>) -->
<role rolename="manager-script"/>
<user username="deployer" password="Use-A-Long-Random-Password-42" roles="manager-script"/>
sudo -u tomcat /opt/tomcat/bin/shutdown.sh && sleep 3 && sudo -u tomcat /opt/tomcat/bin/startup.sh
sleep 5
MANAGER="http://localhost:8080/manager/text"
AUTH="deployer:Use-A-Long-Random-Password-42"

curl -s -u "$AUTH" -T /tmp/student-portal.war "$MANAGER/deploy?path=/student-portal&update=true"
curl -s -u "$AUTH" "$MANAGER/list"
OK - Deployed application at context path [/student-portal]
OK - Listed applications for virtual host [localhost]
/:running:0:ROOT
/manager:running:0:manager
/student-portal:running:0:student-portal

Manager Text Commands

CommandExample URLEffect
deploy/deploy?path=/app&update=true (with -T app.war)Upload and deploy, replacing any old version
list/listShow apps, state and active sessions
reload/reload?path=/appRestart one app without restarting Tomcat
stop / start/stop?path=/appStop or start one app
undeploy/undeploy?path=/appRemove the app and its files
curl -s -u "$AUTH" "$MANAGER/reload?path=/student-portal"
curl -s -u "$AUTH" "$MANAGER/undeploy?path=/student-portal"
OK - Reloaded application with context path [/student-portal]
OK - Undeployed application at context path [/student-portal]

How it works:

  • curl -T file sends the WAR as an HTTP PUT body. Tomcat saves it and deploys it, so you need no SSH access to webapps.
  • Every answer starts with OK or FAIL, which makes the API easy to check in scripts.
  • The list columns are context path, state, active sessions and app name.

Note: By default the Manager app accepts requests only from localhost (a RemoteAddrValve in webapps/manager/META-INF/context.xml). Call it on the server itself or through an SSH tunnel, and never expose /manager to the internet.


Read Tomcat Logs After a WAR Deployment

When a deployment fails, the answer is almost always in logs/.

FileContains
catalina.outEverything printed to stdout/stderr, including startup errors
catalina.YYYY-MM-DD.logTomcat's own log messages for that day
localhost.YYYY-MM-DD.logErrors thrown by your servlets and filters
localhost_access_log.YYYY-MM-DD.txtOne line per HTTP request
tail -n 3 /opt/tomcat/logs/localhost_access_log.$(date +%F).txt
grep -A3 "SEVERE" /opt/tomcat/logs/catalina.out | tail -n 4
127.0.0.1 - - [18/Nov/2026:10:42:07 +0530] "GET /student-portal/hello?name=Asha HTTP/1.1" 200 13
127.0.0.1 - deployer [18/Nov/2026:10:44:31 +0530] "PUT /manager/text/deploy?path=/student-portal&update=true HTTP/1.1" 200 60
127.0.0.1 - - [18/Nov/2026:10:44:33 +0530] "GET /student-portal/status HTTP/1.1" 200 84
SEVERE [Catalina-utility-2] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file

How it works:

  • The access log shows the status code for each request: 200 means the app answered; 404 usually means a wrong context path.
  • A SEVERE line saying listeners or servlets "failed to start" points to an exception in init() or a ServletContextListener. The full stack trace is in localhost.<date>.log.

Real-World Example: Java WAR Deployment Script With Rollback

This script deploys a new versioned WAR next to the running one using Tomcat parallel deployment (##version), checks the /status page from the WAR lesson, and then removes the old version. If the new version fails its check, it undeploys the new version and the old one keeps serving users.

#!/usr/bin/env bash
# deploy-war.sh <war-file> <deploy-label>   e.g. deploy-war.sh build/student-portal.war 003
set -euo pipefail
WAR_FILE="$1"
NEW_LABEL="$2"
CONTEXT="/student-portal"
MANAGER="http://localhost:8080/manager/text"
AUTH="deployer:${TOMCAT_DEPLOY_PASSWORD:?set TOMCAT_DEPLOY_PASSWORD}"

manager() { curl -fsS -u "$AUTH" "$@"; }

# find the label of the version that is running now (empty if none)
OLD_LABEL=$(manager "$MANAGER/list" | grep "^$CONTEXT:running" | sed -n 's/.*##//p' | tail -n 1)
echo "==> Running version: ${OLD_LABEL:-none}"

echo "==> Deploying version $NEW_LABEL"
manager -T "$WAR_FILE" "$MANAGER/deploy?path=$CONTEXT&version=$NEW_LABEL"

echo "==> Checking new version"
for i in $(seq 1 20); do
  STATUS=$(curl -fs "http://localhost:8080$CONTEXT/status" || true)
  if [[ "$STATUS" == *"\"deploy\":\"$NEW_LABEL\""* ]]; then
    echo "==> Healthy: $STATUS"
    if [[ -n "$OLD_LABEL" ]]; then
      manager "$MANAGER/undeploy?path=$CONTEXT&version=$OLD_LABEL"
    fi
    echo "==> Done: $NEW_LABEL is live"
    exit 0
  fi
  sleep 0.5
done

echo "==> Version $NEW_LABEL failed its check, removing it"
manager "$MANAGER/undeploy?path=$CONTEXT&version=$NEW_LABEL" || true
echo "==> Still serving: ${OLD_LABEL:-nothing}"
exit 1

A successful release from version 002 to 003:

export TOMCAT_DEPLOY_PASSWORD='Use-A-Long-Random-Password-42'
./deploy-war.sh "target/student-portal##003.war" 003
==> Running version: 002
==> Deploying version 003
OK - Deployed application at context path [/student-portal] version [003]
==> Checking new version
==> Healthy: {"app":"student-portal","version":"3.0.0","deploy":"003","context":"/student-portal"}
OK - Undeployed application at context path [/student-portal] version [002]
==> Done: 003 is live

A broken build 004 whose init() throws an exception:

./deploy-war.sh "target/student-portal##004.war" 004; echo "exit=$?"
==> Running version: 003
==> Deploying version 004
FAIL - Deployed application at context path [/student-portal] version [004] but context failed to start
==> Version 004 failed its check, removing it
OK - Undeployed application at context path [/student-portal] version [004]
==> Still serving: 003
exit=1

How it works:

  1. Find the live version. The list output contains student-portal##003; sed keeps only the text after ##.
  2. Deploy side by side. The version= parameter tells Tomcat to deploy the WAR as a new version of the same context path. Both versions run at once, and new sessions go to the newest version that started successfully.
  3. Health-gated switch. The script waits until /status reports the new deploy label. Only then is the old version undeployed, so users never see an empty server.
  4. Automatic rollback. If the new version fails to start, Tomcat answers FAIL and new requests keep going to the old version. Because curl -f does not treat a FAIL text body as an HTTP error, the loop still runs, sees no healthy response and undeploys the broken version. The exit code 1 marks the CI job as failed.
  5. No passwords in the script. The Manager password comes from the TOMCAT_DEPLOY_PASSWORD environment variable, and :? stops the script with a clear message if it is missing. To restart Tomcat automatically after a reboot, the next lesson, Run Java as a Service, runs Tomcat under systemd.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java WAR Deployment and get answers drawn from it.

Signed-in readers only.