One place for hosting & domains

      Tomcat

      Cómo instalar Apache Tomcat 9 en Ubuntu 18.04


      Introducción

      Apache Tomcat es un servidor web y contenedor de servlets que se utiliza para presentar aplicaciones Java. Tomcat es una implementación de código abierto de las tecnologías Java Servlet y JavaServer Pages publicada por la Apache Software Foundation. En este tutorial se abordan la instalación básica y algunas configuraciones de la última versión de Tomcat 9 en su servidor Ubuntu 18.04.

      Requisitos previos

      Antes de comenzar con esta guía, debe disponer de un usuario no root con privilegios sudo configurado en su servidor. Puede aprender a hacer esto completando nuestra guía de configuración inicial para servidores de Ubuntu 16.04.

      Paso 1: Instalar Java

      Para que sea posible ejecutar cualquier código de aplicaciones web Java, es necesario que Tomcat esté instalado en el servidor. Podemos cumplir con ese requisito instalando OpenJDK con apt.

      Primero, actualice su índice de paquetes de apt:

      A continuación, instale el paquete del Kit de desarrollo Jave con apt:

      • sudo apt install default-jdk

      Ahora que Java está instalado, podremos crear un usuario tomcat, que usaremos para ejecutar el servicio de Tomcat.

      Paso 2: Crear un usuario tomcat

      Por seguridad, Tomcat debería ejecutarse como un usuario sin privilegios (es decir, no root). Crearemos un nuevo usuario y grupo que ejecutarán el servicio de Tomcat.

      Primero, cree un nuevo grupo tomcat:

      A continuación, cree un nuevo usuario tomcat. Haremos que este usuario sea miembro del grupo tomcat, con un directorio de inicio /opt/tomcat (donde instalaremos Tomcat) y un shell de /bin/false (de modo que nadie pueda iniciar sesión en la cuenta):

      • sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat

      Ahora que nuestro usuario tomcat está configurado, descargaremos e instalaremos Tomcat.

      Paso 3: Instalar Tomcat

      La mejor alternativa para instalar Tomcat 9 es descargar la última versión binaria y luego configurarla manualmente.

      Busque la última versión de Tomcat 9 en la página de descargas de Tomcat 9. En el momento en que se redactó esta guía, la versión más reciente fue la 9.0.10, pero debería usar una versión estable posterior si se encuentra disponible. En la sección Binary Distributions, debajo de la lista de Core, copie el enlace a “tar.gz”.

      A continuación, posiciónese en el directorio /tmp en su servidor. Este es un buen directorio para descargar los elementos ephemeral como el tarball de Tomcat, que no necesitaremos tras extraer el contenido de Tomcat:

      Utilice curl para descargar el enlace que copió desde el sitio web de Tomcat:

      • curl -O http://mirror.cc.columbia.edu/pub/software/apache/tomcat/tomcat-9/v9.0.10/bin/apache-tomcat-9.0.10.tar.gz

      Instalaremos Tomcat en el directorio /opt/tomcat. Cree el directorio y luego extraiga el archivo con estos comandos:

      • sudo mkdir /opt/tomcat
      • sudo tar xzvf apache-tomcat-9*tar.gz -C /opt/tomcat --strip-components=1

      A continuación, podremos configurar los permisos de usuario adecuados para nuestra instalación.

      Paso 4: Actualizar los permisos

      El usuario tomcat que configuramos debe tener acceso a la instalación de Tomcat. Configuraremos esto ahora.

      Posiciónese en el directorio en el que desempaquetamos la instalación de Tomcat:

      Otorgue la propiedad sobre todo el directorio de instalación al grupo tomcat:

      • sudo chgrp -R tomcat /opt/tomcat

      A continuación, proporcione al grupo tomcat acceso de lectura al directorio conf y a todos sus contenidos, y acceso de ejecución al directorio:

      • sudo chmod -R g+r conf
      • sudo chmod g+x conf

      Asegúrese de que el usuario tomcat sea el propietario de los directorios webapps, work, temp y logs:

      • sudo chown -R tomcat webapps/ work/ temp/ logs/

      Ahora que están configurados los permisos adecuados, podemos crear un archivo de servicio systemd para gestionar el proceso de Tomcat.

      Paso 5: Crear un archivo de servicio de systemd

      Nos convendrá poder ejecutar Tomcat como servicio; por ello, configuraremos el servicio systemd.

      Tomcat necesita saber dónde está instalado Java. Esta ruta se denomina comúnmente “JAVA_HOME”. La alternativa más sencilla para revisar esa ubicación es ejecutar el siguiente comando:

      • sudo update-java-alternatives -l

      Output

      java-1.11.0-openjdk-amd64 1081 /usr/lib/jvm/java-1.11.0-openjdk-amd64

      Su JAVA_HOME es el resultado de la última columna (resaltada en rojo). Considerando el ejemplo anterior, el JAVA_HOME correcto para este servidor sería el siguiente:

      JAVA_HOME

      /usr/lib/jvm/java-1.11.0-openjdk-amd64

      Es posible que su JAVA_HOME sea diferente.

      Con esta información, podemos crear el archivo de servicio systemd. Abra un archivo llamado tomcat.service en el directorio /etc/systemd/system escribiendo lo siguiente:

      • sudo nano /etc/systemd/system/tomcat.service

      Pegue el siguiente contenido en su archivo de servicio. Modifique el valor de JAVA_HOME si es necesario para que coincida con el valor que encontró en su sistema. Es posible que también desee modificar los ajustes de asignación de memoria especificados en CATALINA_OPTS:

      /etc/systemd/system/tomcat.service

      [Unit]
      Description=Apache Tomcat Web Application Container
      After=network.target
      
      [Service]
      Type=forking
      
      Environment=JAVA_HOME=/usr/lib/jvm/java-1.11.0-openjdk-amd64
      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
      

      Cuando termine, guarde y cierre el archivo.

      A continuación, vuelva a cargar el demonio systemd para que reciba información sobre nuestro archivo de servicio:

      • sudo systemctl daemon-reload

      Inicie el servicio Tomcat escribiendo lo siguiente:

      • sudo systemctl start tomcat

      Compruebe que se inició sin errores escribiendo lo siguiente:

      • sudo systemctl status tomcat

      Paso 6: Aplicar ajustes al firewall y probar el servidor de Tomcat

      Ahora que se inició el servicio de Tomcat, podemos probarlo para garantizar que la página predeterminada está disponible.

      Antes de hacer esto, debemos realizar ajustes en el firewall para permitir que nuestras solicitudes lleguen al servicio. Si cumplió con los requisitos previos, en este momento dispondrá de un firewall ufw habilitado.

      Tomcat utiliza el puerto 8080 para aceptar solicitudes convencionales. Permita el tráfico hacia este puerto escribiendo lo siguiente:

      Una vez modificado firewall, podrá acceder a la página de presentación predeterminada agregando a su dominio o dirección IP la terminación :8080 y visitándolos en un navegador web:

      Open in web browser

      http://server_domain_or_IP:8080

      Verá la página de presentación de Tomcat predeterminada e información adicional. Sin embargo, si hace clic en los enlaces de de la aplicación de administración, por ejemplo, se denegará el acceso. Podemos configurar ese acceso a continuación.

      Si pudo acceder correctamente a Tomcat, será un buen momento para habilitar el archivo de servicio a fin de que Tomcat se inicie automáticamente en el inicio:

      • sudo systemctl enable tomcat

      Paso 7: Configurar la interfaz de administración web de Tomcat

      Para usar la aplicación de administración web que viene con Tomcat, debemos añadir un inicio de sesión a nuestro servidor de Tomcat. Haremos esto editando el archivo tomcat-users.xml:

      • sudo nano /opt/tomcat/conf/tomcat-users.xml

      Le convendrá añadir un usuario que pueda acceder a manager-gui y admin-gui (aplicaciones web que vienen con Tomcat). Puede hacerlo definiendo un usuario, similar al ejemplo que se muestra a continuación, entre las etiquetas tomcat-users. Asegúrese de cambiar el nombre de usuario y la contraseña por opciones seguras.

      tomcat-users.xml — Admin User

      <tomcat-users . . .>
          <user username="admin" password="password" roles="manager-gui,admin-gui"/>
      </tomcat-users>
      

      Guarde y cierre el archivo cuando termine.

      Por defecto, las versiones más recientes de Tomcat impiden que las aplicaciones provenientes del propio servidor accedan a las aplicaciones Manager y Host Manager. Debido a que la instalación se realizará en una máquina remota, probablemente le convenga eliminar o alterar esta restricción. Para cambiar las restricciones de direcciones IP en estas, abra los archivos context.xml correspondientes.

      Para la aplicación Manager, escriba lo siguiente:

      • sudo nano /opt/tomcat/webapps/manager/META-INF/context.xml

      Para la aplicación Host Manager, escriba esto:

      • sudo nano /opt/tomcat/webapps/host-manager/META-INF/context.xml

      En el interior, elimine la restricción de direcciones IP para permitir las conexiones desde cualquier lugar. Además, si desea permitir el acceso únicamente a las conexiones que provienen de su propia dirección IP, puede añadir su dirección IP pública a la lista:

      context.xml files for Tomcat webapps

      <Context antiResourceLocking="false" privileged="true" >
        <!--<Valve className="org.apache.catalina.valves.RemoteAddrValve"
               allow="127.d+.d+.d+|::1|0:0:0:0:0:0:0:1" />-->
      </Context>
      

      Guarde y cierre los archivos cuando termine.

      Para implementar los cambios que realizamos, reinicie el servicio de Tomcat:

      • sudo systemctl restart tomcat

      Paso 8: Acceder a la interfaz web

      Ahora que creamos un usuario, podremos acceder a la interfaz de administración web en un navegador web. De nuevo, puede acceder a la interfaz correcta introduciendo el nombre de dominio o la dirección IP de su servidor seguido del puerto 8080 en su navegador:

      Open in web browser

      http://server_domain_or_IP:8080

      La página que ve sería la misma que se cargó cuando realizó la prueba anteriormente:

      root de Tomcat

      Veamos Manager App. Se puede acceder a ella a través del enlace o con http://server_domain_or_IP:80/manager/html. Deberá introducir las credenciales de la cuenta que agregó al archivo tomcat-users.xml. Después de eso, debería ver una página similar a esta:

      Administrador de aplicaciones web de Tomcat

      El Administrador de aplicaciones web se utiliza para gestionar sus aplicaciones Java. En él puede concretar inicios, detenciones, recargas e implementaciones y detener estas últimas. También puede ejecutar algunos diagnósticos en sus aplicaciones (es decir, encontrar fugas de memoria). Por último, la información sobre su servidor está disponible en la parte inferior de esta página.

      Ahora veremos Host Manager, al que se puede acceder a través del enlace o con http://server_domain_or_IP:80/host-manager/html/:

      Host Manager virtual de Tomcat

      Desde la página de Virtual Host Manager, puede añadir hosts virtuales desde los cuales proporcionará sus aplicaciones.

      Conclusión

      ¡Completó la instalación de Tomcat! Ahora puede implementar sus propias aplicaciones web Java.

      En este momento, su instalación de Tomcat funciona, pero no está completamente cifrada. Esto significa que todos los datos, incluidos los elementos confidenciales como las contraseñas, se envían en texto sin formato, que otros pueden interceptar y leer en Internet. Para evitar que esto suceda, se le recomienda encarecidamente cifrar sus conexiones con SSL. Puede obtener información sobre cómo cifrar su conexión con Tomcat siguiendo esta guía (tenga en cuenta que en ella se abarca el cifrado de Tomcat 8 en Ubuntu 16.04).



      Source link

      How To Install Apache Tomcat 9 on Debian 10

      Introduction

      Apache Tomcat is a web server and servlet container that is used to serve Java applications. Tomcat is an open source implementation of the Java Servlet and JavaServer Pages technologies, released by the Apache Software Foundation. This tutorial covers the basic installation and some configuration of the latest release of Tomcat 9 on your Debian 10 server.

      Prerequisites

      Before you begin with this guide, you should have a non-root user with sudo privileges set up on your server. You can learn how to do this by completing our Debian 10 initial server setup guide.

      Step 1 — Install Java

      Tomcat requires Java to be installed on the server so that any Java web application code can be executed. We can satisfy that requirement by installing OpenJDK with apt.

      First, update your apt package index:

      Then install the Java Development Kit package with apt:

      • sudo apt install default-jdk

       

      Now that Java is installed, we can create a tomcat user, which will be used to run the Tomcat service.

      Step 2 — Create Tomcat User

      For security purposes, Tomcat should be run as an unprivileged user (i.e. not root). We will create a new user and group that will run the Tomcat service.

      First, create a new tomcat group:

      Next, create a new tomcat user. We’ll make this user a member of the tomcat group, with a home directory of /opt/tomcat (where we will install Tomcat), and with a shell of /bin/false (so nobody can log into the account):

      • sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat

       

      Now that our tomcat user is set up, let’s download and install Tomcat.

      Step 3 — Install Tomcat

      The best way to install Tomcat 9 is to download the latest binary release then configure it manually.

      Find the latest version of Tomcat 9 at the Tomcat 9 Downloads page. At the time of writing, the latest version is 9.0.27, but you should use a later stable version if it is available. Under the Binary Distributions section, then under the Core list, copy the link to the “tar.gz”.

      Next, return to your SSH session and move to the /tmp directory on your server. This is a good directory to download ephemeral items, like the Tomcat tarball, which we won’t need after extracting the Tomcat contents:

      We’ll use the curl command-line tool to download the tarball. Install curl:

      Now, use curl to download the link that you copied from the Tomcat website:

      • curl -O http://www-eu.apache.org/dist/tomcat/tomcat-9/v9.0.11/bin/apache-tomcat-9.0.11.tar.gz

       

      We will install Tomcat to the /opt/tomcat directory. Create the directory, then extract the archive to it with these commands:

      • sudo mkdir /opt/tomcat
      • sudo tar xzvf apache-tomcat-9*tar.gz -C /opt/tomcat –strip-components=1

       

      Next, we will set up the proper user permissions for our installation.

      Step 4 — Update Permissions

      The tomcat user that we created needs to have access to the Tomcat installation. We’ll set that up now.

      Change to the directory where we unpacked the Tomcat installation:

      Give the tomcat group ownership over the entire installation directory:

      • sudo chgrp -R tomcat /opt/tomcat

       

      Next, give the tomcat group read access to the conf directory and all of its contents, and execute access to the directory itself:

      • sudo chmod -R g+r conf
      • sudo chmod g+x conf

       

      Make the tomcat user the owner of the webapps, work, temp, and logs directories:

      • sudo chown -R tomcat webapps/ work/ temp/ logs/

       

      Now that the proper permissions are set up, we will create a systemd service file to manage the Tomcat process.

      Step 5 — Create a systemd Service File

      We want to be able to run Tomcat as a service, so we will set up systemd service file.

      Tomcat needs to know where Java is installed. This path is commonly referred to as JAVA_HOME. The easiest way to look up that location is by running this command:

      • sudo update-java-alternatives -l

       

      Output

      java-1.11.0-openjdk-amd64 1111 /usr/lib/jvm/java-1.11.0-openjdk-amd64

      Your JAVA_HOME is the output from the last column (highlighted above). Given the example above, the correct JAVA_HOME for this server would be:

      JAVA_HOME

      /usr/lib/jvm/java-1.11.0-openjdk-amd64

      Your JAVA_HOME may be different.

      With this piece of information, we can create the systemd service file. Open a file called tomcat.service in the /etc/systemd/system directory by typing:

      • sudo nano /etc/systemd/system/tomcat.service

       

      Paste the following contents into your service file. Modify the value of JAVA_HOME if necessary to match the value you found on your system. You may also want to modify the memory allocation settings that are specified in CATALINA_OPTS:

      /etc/systemd/system/tomcat.service

      [Unit]
      Description=Apache Tomcat Web Application Container
      After=network.target
      
      [Service]
      Type=forking
      
      Environment=JAVA_HOME=/usr/lib/jvm/java-1.11.0-openjdk-amd64
      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
      

      When you are finished, save and close the file.

      Next, reload the systemd daemon so that it knows about our service file:

      • sudo systemctl daemon-reload

       

      Start the Tomcat service by typing:

      • sudo systemctl start tomcat

       

      Double check that it started without errors by typing:

      • sudo systemctl status tomcat

       

      You should see output similar to the following:

      Output

      ● tomcat.service – Apache Tomcat Web Application Container Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: enabled) Active: active (running) since Thu 2019-10-24 17:18:11 UTC; 4s ago Process: 5962 ExecStart=/opt/tomcat/bin/startup.sh (code=exited, status=0/SUCCESS) Main PID: 5970 (java) Tasks: 44 (limit: 2377) Memory: 184.2M CGroup: /system.slice/tomcat.service └─5970 /usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java -Djava.util.logging.config.file=/opt/tomcat/conf/logging.properties -Djava.u Oct 24 17:18:10 tomcat systemd[1]: Starting Apache Tomcat Web Application Container… Oct 24 17:18:11 tomcat startup.sh[5962]: Tomcat started. Oct 24 17:18:11 tomcat systemd[1]: Started Apache Tomcat Web Application Container.

      This confirms that Tomcat is up and running on your server.

      Step 6 — Adjust the Firewall and Test the Tomcat Server

      Now that the Tomcat service is started, we can test to make sure the default page is available.

      Before we do that, we need to adjust the firewall to allow our requests to get to the service. If you followed the prerequisites, you will have a ufw firewall enabled currently.

      Tomcat uses port 8080 to accept requests. Allow traffic to that port by typing:

      With the firewall modified, you can access the default splash page by going to your domain or IP address followed by :8080 in a web browser:

      Open in web browser

      http://server_domain_or_IP:8080

      You will see the default Tomcat splash page, in addition to other information. However, if you click the links for the Manager App, for instance, you will be denied access. We can configure that access next.

      If you were able to successfully access Tomcat, now is a good time to enable the service file so that Tomcat automatically starts at boot:

      • sudo systemctl enable tomcat

       

      Step 7 — Configure Tomcat Web Management Interface

      In order to use the manager web app that comes with Tomcat, we must add a login to our Tomcat server. We will do this by editing the tomcat-users.xml file:

      • sudo nano /opt/tomcat/conf/tomcat-users.xml

       

      You will want to add a user who can access the manager-gui and admin-gui (web apps that come with Tomcat). You can do so by defining a user, similar to the example below, between the tomcat-users tags. Be sure to change the username and password to something secure:

      tomcat-users.xml

      <tomcat-users>
      . . .
          <user username="admin" password="password" roles="manager-gui,admin-gui"/>
      </tomcat-users>
      

      Save and close the file when you are finished.

      By default, newer versions of Tomcat restrict access to the Manager and Host Manager apps to connections coming from the server itself. Since we are installing on a remote machine, you will probably want to remove or alter this restriction. To change the IP address restrictions on these, open the appropriate context.xml files.

      For the Manager app, type:

      • sudo nano /opt/tomcat/webapps/manager/META-INF/context.xml

       

      For the Host Manager app, type:

      • sudo nano /opt/tomcat/webapps/host-manager/META-INF/context.xml

       

      Inside, comment out the IP address restriction to allow connections from anywhere. Alternatively, if you would like to allow access only to connections coming from your own IP address, you can add your public IP address to the list:

      context.xml files for Tomcat webapps

      <Context antiResourceLocking="false" privileged="true" >
        <!--<Valve className="org.apache.catalina.valves.RemoteAddrValve"
               allow="127.d+.d+.d+|::1|0:0:0:0:0:0:0:1" />-->
      </Context>
      

      Save and close the files when you are finished.

      To put our changes into effect, restart the Tomcat service:

      • sudo systemctl restart tomcat

       

      Step 8 — Access the Web Interface

      Now that we have create a user, we can access the web management interface again in a web browser. Once again, you can get to the correct interface by entering your server’s domain name or IP address followed on port 8080 in your browser:

      Open in web browser

      http://server_domain_or_IP:8080

      The page you see should be the same one you were given when you tested earlier:

      Tomcat root

      Let’s take a look at the Manager App, accessible via the link or http://server_domain_or_IP:8080/manager/html. You will need to enter the account credentials that you added to the tomcat-users.xml file. Afterwards, you should see a page that looks like this:

      Tomcat Web Application Manager

      The Web Application Manager is used to manage your Java applications. You can Start, Stop, Reload, Deploy, and Undeploy here. You can also run some diagnostics on your apps (i.e. find memory leaks). Lastly, information about your server is available at the very bottom of this page.

      Now let’s take a look at the Host Manager, accessible via the link or http://server_domain_or_IP:8080/host-manager/html/:

      Tomcat Virtual Host Manager

      From the Virtual Host Manager page, you can add virtual hosts to serve your applications from.

      Conclusion

      Your installation of Tomcat is complete! You are now free to deploy your own Java web applications.

      Currently, your Tomcat installation is functional, but entirely unencrypted. This means that all data, including sensitive items like passwords, are sent in plain text that can be intercepted and read by other parties on the internet. In order to prevent this from happening, it is strongly recommended that you encrypt your connections with SSL. You can find out how to encrypt your connections to Tomcat by following this guide (note: this guide covers Tomcat 8 encryption on Ubuntu 16.04).

      Source link

      How To Install Apache Tomcat 9 on Debian 9


      Introduction

      Apache Tomcat is a web server and servlet container that is used to serve Java applications. Tomcat is an open source implementation of the Java Servlet and JavaServer Pages technologies, released by the Apache Software Foundation. This tutorial covers the basic installation and some configuration of the latest release of Tomcat 9 on your Debian 9 server.

      Prerequisites

      Before you begin with this guide, you should have a non-root user with sudo privileges set up on your server. You can learn how to do this by completing our Debian 9 initial server setup guide.

      Step 1 — Install Java

      Tomcat requires Java to be installed on the server so that any Java web application code can be executed. We can satisfy that requirement by installing OpenJDK with apt.

      First, update your apt package index:

      Then install the Java Development Kit package with apt:

      • sudo apt install default-jdk

      Now that Java is installed, we can create a tomcat user, which will be used to run the Tomcat service.

      Step 2 — Create Tomcat User

      For security purposes, Tomcat should be run as an unprivileged user (i.e. not root). We will create a new user and group that will run the Tomcat service.

      Note: In some environments, a package called unscd may be installed by default in order to speed up requests to name servers like LDAP. The most recent version currently available in Debian contains a bug that causes certain commands (like the adduser command below) to produce additional output that looks like this:

      sent invalidate(passwd) request, exiting
      sent invalidate(group) request, exiting
      

      These messages are harmless, but if you wish to avoid them, it is safe to remove the unscd package if you do not not plan on using systems like LDAP for user information:

      First, create a new tomcat group:

      Next, create a new tomcat user. We'll make this user a member of the tomcat group, with a home directory of /opt/tomcat (where we will install Tomcat), and with a shell of /bin/false (so nobody can log into the account):

      • sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat

      Now that our tomcat user is set up, let's download and install Tomcat.

      Step 3 — Install Tomcat

      The best way to install Tomcat 9 is to download the latest binary release then configure it manually.

      Find the latest version of Tomcat 9 at the Tomcat 9 Downloads page. At the time of writing, the latest version is 9.0.11, but you should use a later stable version if it is available. Under the Binary Distributions section, then under the Core list, copy the link to the "tar.gz".

      Next, change to the /tmp directory on your server. This is a good directory to download ephemeral items, like the Tomcat tarball, which we won't need after extracting the Tomcat contents:

      We’ll use the curl command-line tool to download the tarball. Install curl:

      Now, use curl to download the link that you copied from the Tomcat website:

      • curl -O http://www-eu.apache.org/dist/tomcat/tomcat-9/v9.0.11/bin/apache-tomcat-9.0.11.tar.gz

      We will install Tomcat to the /opt/tomcat directory. Create the directory, then extract the archive to it with these commands:

      • sudo mkdir /opt/tomcat
      • sudo tar xzvf apache-tomcat-9*tar.gz -C /opt/tomcat --strip-components=1

      Next, we can set up the proper user permissions for our installation.

      Step 4 — Update Permissions

      The tomcat user that we set up needs to have access to the Tomcat installation. We'll set that up now.

      Change to the directory where we unpacked the Tomcat installation:

      Give the tomcat group ownership over the entire installation directory:

      • sudo chgrp -R tomcat /opt/tomcat

      Next, give the tomcat group read access to the conf directory and all of its contents, and execute access to the directory itself:

      • sudo chmod -R g+r conf
      • sudo chmod g+x conf

      Make the tomcat user the owner of the webapps, work, temp, and logs directories:

      • sudo chown -R tomcat webapps/ work/ temp/ logs/

      Now that the proper permissions are set up, we can create a systemd service file to manage the Tomcat process.

      Step 5 — Create a systemd Service File

      We want to be able to run Tomcat as a service, so we will set up systemd service file.

      Tomcat needs to know where Java is installed. This path is commonly referred to as "JAVA_HOME". The easiest way to look up that location is by running this command:

      • sudo update-java-alternatives -l

      Output

      java-1.8.0-openjdk-amd64 1081 /usr/lib/jvm/java-1.8.0-openjdk-amd64

      Your JAVA_HOME is the output from the last column (highlighted in red). Given the example above, the correct JAVA_HOME for this server would be:

      JAVA_HOME

      /usr/lib/jvm/java-1.8.0-openjdk-amd64

      Your JAVA_HOME may be different.

      With this piece of information, we can create the systemd service file. Open a file called tomcat.service in the /etc/systemd/system directory by typing:

      • sudo nano /etc/systemd/system/tomcat.service

      Paste the following contents into your service file. Modify the value of JAVA_HOME if necessary to match the value you found on your system. You may also want to modify the memory allocation settings that are specified in CATALINA_OPTS:

      /etc/systemd/system/tomcat.service

      [Unit]
      Description=Apache Tomcat Web Application Container
      After=network.target
      
      [Service]
      Type=forking
      
      Environment=JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64
      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
      

      When you are finished, save and close the file.

      Next, reload the systemd daemon so that it knows about our service file:

      • sudo systemctl daemon-reload

      Start the Tomcat service by typing:

      • sudo systemctl start tomcat

      Double check that it started without errors by typing:

      • sudo systemctl status tomcat

      You should see output similar to the following:

      Output

      ● tomcat.service - Apache Tomcat Web Application Container Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: enabled) Active: active (running) since Wed 2018-09-05 20:47:44 UTC; 3s ago Process: 9037 ExecStart=/opt/tomcat/bin/startup.sh (code=exited, status=0/SUCCESS) Main PID: 9046 (java) Tasks: 46 (limit: 4915) CGroup: /system.slice/tomcat.service └─9046 /usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -Djava.util.logging.config.file=/opt/tomcat/conf/logging.properties -Dja Sep 05 20:47:44 tomcat systemd[1]: Starting Apache Tomcat Web Application Container... Sep 05 20:47:44 tomcat systemd[1]: Started Apache Tomcat Web Application Container.

      This confirms that Tomcat is up and running on your server.

      Step 6 — Adjust the Firewall and Test the Tomcat Server

      Now that the Tomcat service is started, we can test to make sure the default page is available.

      Before we do that, we need to adjust the firewall to allow our requests to get to the service. If you followed the prerequisites, you will have a ufw firewall enabled currently.

      Tomcat uses port 8080 to accept conventional requests. Allow traffic to that port by typing:

      With the firewall modified, you can access the default splash page by going to your domain or IP address followed by :8080 in a web browser:

      Open in web browser

      http://server_domain_or_IP:8080

      You will see the default Tomcat splash page, in addition to other information. However, if you click the links for the Manager App, for instance, you will be denied access. We can configure that access next.

      If you were able to successfully accessed Tomcat, now is a good time to enable the service file so that Tomcat automatically starts at boot:

      • sudo systemctl enable tomcat

      Step 7 — Configure Tomcat Web Management Interface

      In order to use the manager web app that comes with Tomcat, we must add a login to our Tomcat server. We will do this by editing the tomcat-users.xml file:

      • sudo nano /opt/tomcat/conf/tomcat-users.xml

      You will want to add a user who can access the manager-gui and admin-gui (web apps that come with Tomcat). You can do so by defining a user, similar to the example below, between the tomcat-users tags. Be sure to change the username and password to something secure:

      tomcat-users.xml — Admin User

      <tomcat-users . . .>
          <user username="admin" password="password" roles="manager-gui,admin-gui"/>
      </tomcat-users>
      

      Save and close the file when you are finished.

      By default, newer versions of Tomcat restrict access to the Manager and Host Manager apps to connections coming from the server itself. Since we are installing on a remote machine, you will probably want to remove or alter this restriction. To change the IP address restrictions on these, open the appropriate context.xml files.

      For the Manager app, type:

      • sudo nano /opt/tomcat/webapps/manager/META-INF/context.xml

      For the Host Manager app, type:

      • sudo nano /opt/tomcat/webapps/host-manager/META-INF/context.xml

      Inside, comment out the IP address restriction to allow connections from anywhere. Alternatively, if you would like to allow access only to connections coming from your own IP address, you can add your public IP address to the list:

      context.xml files for Tomcat webapps

      <Context antiResourceLocking="false" privileged="true" >
        <!--<Valve className="org.apache.catalina.valves.RemoteAddrValve"
               allow="127.d+.d+.d+|::1|0:0:0:0:0:0:0:1" />-->
      </Context>
      

      Save and close the files when you are finished.

      To put our changes into effect, restart the Tomcat service:

      • sudo systemctl restart tomcat

      Step 8 — Access the Web Interface

      Now that we have create a user, we can access the web management interface again in a web browser. Once again, you can get to the correct interface by entering your server's domain name or IP address followed on port 8080 in your browser:

      Open in web browser

      http://server_domain_or_IP:8080

      The page you see should be the same one you were given when you tested earlier:

      Tomcat root

      Let's take a look at the Manager App, accessible via the link or http://server_domain_or_IP:8080/manager/html. You will need to enter the account credentials that you added to the tomcat-users.xml file. Afterwards, you should see a page that looks like this:

      Tomcat Web Application Manager

      The Web Application Manager is used to manage your Java applications. You can Start, Stop, Reload, Deploy, and Undeploy here. You can also run some diagnostics on your apps (i.e. find memory leaks). Lastly, information about your server is available at the very bottom of this page.

      Now let's take a look at the Host Manager, accessible via the link or http://server_domain_or_IP:8080/host-manager/html/:

      Tomcat Virtual Host Manager

      From the Virtual Host Manager page, you can add virtual hosts to serve your applications from.

      Conclusion

      Your installation of Tomcat is complete! Your are now free to deploy your own Java web applications!

      Currently, your Tomcat installation is functional, but entirely unencrypted. This means that all data, including sensitive items like passwords, are sent in plain text that can be intercepted and read by other parties on the internet. In order to prevent this from happening, it is strongly recommended that you encrypt your connections with SSL. You can find out how to encrypt your connections to Tomcat by following this guide (note: this guide covers Tomcat 8 encryption on Ubuntu 16.04).



      Source link