Before installing Tomcat, ensure that Java is installed. You can follow this post to install Java 8. The first step is to run Tomcat as a user without root privileges.
sudo groupadd tomcat
sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat
Next, download Tomcat:
cd /tmp
wget http://apache.is.co.za/tomcat/tomcat-8/v8.5.23/bin/apache-tomcat-8.5.23.tar.gz
Create the Tomcat directory and untar the file:
sudo mkdir /opt/tomcat
sudo tar xzvf apache-tomcat-8*tar.gz -C /opt/tomcat --strip-components=1
Next, update permissions and ownership:
cd /opt/tomcat
sudo chgrp -R tomcat /opt/tomcat
sudo chmod -R g+r conf
sudo chmod g+x conf
sudo chown -R tomcat webapps/ work/ temp/ logs/
The final step is run Tomcat as a service.
We need to get the path to Java in order to continue:
sudo update-java-alternatives -l
Copy the path, and paste in the section reading PASTE-HERE below:
[Unit]
Description=Apache Tomcat Web Application Container
After=network.target
[Service]
Type=forking
Environment=JAVA_HOME=PASTE-HERE/jre
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment=CATALINA_BASE=/opt/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'
ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/opt/tomcat/bin/shutdown.sh
User=tomcat
Group=tomcat
UMask=0007
RestartSec=10
Restart=always
[Install]
WantedBy=multi-user.target
Next, create the tomcat.service file:
sudo nano /etc/systemd/system/tomcat.service
Copy the above snippet and paste in this file. Note the /jre after the Java path obtained above.
Save and close the file, and restart systemctl:
sudo systemctl daemon-reload
You can now use the following commands to start, stop, and restart Tomcat:
sudo service tomcat start
sudo service tomcat stop
sudo service tomcar restart