Run Apache Tomcat as User ‘tomcat’ – Setup Guide

tomcatuser-accounts

I want to run Apache Tomcat on Ubuntu 18 as the (by me created) user tomcat.

I am not using the Ubuntu default Tomcat but instead directly downloaded the tar.gz package from the Tomcat homepage.

I have installed it in /opt.

For security reasons I want to run the tomcat a user tomcat which I created in the following way:

sudo useradd -r -s /bin/false tomcat

Now, I would like to start tomcat using the following script:

#!/bin/bash
/bin/su -s /bin/bash -c "/opt/tomcat/bin/startup.sh" tomcat

When I run this script I get the following output:

ubuntu@server-8x32:/opt/tomcat/bin$ ./start-tomcat.sh 
Password: 

I did not specify a password and since this script is also called from some other automatically executed script I cannot provide a password each time.

So my question is: How do I start Apache Tomcat as the user tomcat without being prompt to enter a password?

Best Answer

Create the tomcat group and this file at /etc/systemd/system/tomcat.service with the contents:

#Systemd unit file for tomcat
[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking


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=/bin/kill -15 $MAINPID

User=tomcat
Group=tomcat
UMask=0007
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target

Start the service with

systemctl start tomcat

That will run the service as tomcat.