Установка tomcat в ubuntu 18.04

5: Настройка веб-интерфейса управления Tomcat

Чтобы использовать менеджер веб-приложений, установленный в разделе 3, нужно добавить логин на сервер Tomcat. Для этого нужно отредактировать файл tomcat-users.xml:

Данный файл содержит комментарии, описывающие, как настраивать файл. Можно удалить все комментарии между следующими двумя строками, или же оставить их закомментированными (чтобы использовать примеры):

Кроме того, нужно добавить пользователя с доступом к manager-gui и admin-gui (интерфейс управления, установленный в третьем разделе руководства). Ниже показано, как можно определить такого пользователя (не забудьте изменить пароль и имя пользователя):

Сохраните и закройте файл tomcat-users.xml. Чтобы активировать изменения, перезапустите Tomcat:

Что такое Apache Tomcat?

Apache Tomcat – это сервер приложений, который используется для обслуживания приложений Java в Интернете. Tomcat – это реализация технологий Java Servlet и Java Server Pages с открытым исходным кодом, разработанная Apache Software Foundation.

Данное руководство охватывает основы установки и настройки Tomcat 7.0.x (последней стабильной версии программы на момент написания статьи) на виртуальном выделенном сервере Ubuntu 14.04.

В Ubuntu существует два основных способа установки Tomcat:

  • Установка с помощью менеджера пакетов apt-get; это самый простой способ.
  • Загрузка бинарного дистрибутива с сайта Apache Tomcat. Данное руководство не охватывает этот метод установки; за инструкциями обратитесь к документации Apache Tomcat.

Данное руководство описывает только первый, наиболее простой способ – использование apt-get.

Обратите внимание: данный менеджер пакетов установит последнюю версию Tomcat, доступную в репозитории Ubuntu, что не всегда является последним релизом Tomcat. Чтобы установить последнюю версию Tomcat, скачайте последний бинарный дистрибутив

TomEE

The Web Profile version of TomEE contains

  • CDI — Apache OpenWebBeans
  • EJB — Apache OpenEJB
  • JPA — Apache OpenJPA
  • JSF — Apache MyFaces
  • JSP — Apache Tomcat
  • JSTL — Apache Tomcat
  • JTA — Apache Geronimo Transaction
  • Servlet — Apache Tomcat
  • Javamail — Apache Geronimo JavaMail
  • Bean Validation — Apache BVal

TomEE+

The TomEE Plus distribution adds the following:

  • JAX-RS — Apache CXF
  • JAX-WS — Apache CXF
  • JMS — Apache ActiveMQ
  • Connector — Apache Geronimo Connector

Microprofile is an open forum to optimize Enterprise Java for a microservices architecture by innovating across multiple implementations and collaborating on common areas of interest with a goal of standardization. TomEE is actively participating in this effort, and would welcome help from the community in moving this process forward.

RebelLabs released an annual study with awards to recognize Geeky Excellence for 2014. Tomcat and TomEE were named as one of the 10 Geek Choice Awards winner. For a complete list of winners, check out the report «10 Kick-Ass Technologies Modern Developers Love».

Principles

Some core principles guide the integration:

  • Don’t mess with Tomcat — Just take it as it comes and extend it
  • Keep it as simple as possible for the end user
  • Avoid architectural overhead — It should just run existing applications out of the box

The desire to beef-up Tomcat installations has persisted despite the existence of full-profile application servers,
many of which actually include Tomcat in some truncated or stripped-down form.
TomEE strives to fill this gap.

Under the Covers

Apache TomEE is assembled from a vanilla Apache Tomcat official distribution.
No picking and choosing individual parts of Tomcat and building a «new» server
leveraging Tomcat. We start with Tomcat, add our jars and configuration and zip up the rest.
The result is Tomcat with added EE features, TomEE.

Tomcat provides plenty of hooks for filling out parts of its lifecycle. We
leverage them all to fill the gaps. The result is a whole lotta sharing!

Servlets now get access to JPA and Transactions, EJBs get access to Tomcat
provided Security. Any Tomcat provided resources, say from a context.xml,
can be looked up or injected by any managed component in the system.

Keep it Tight, Keep it Simple

There’s a definite «less is more» philosophy in Apache TomEE. It’s too
easy to go too far when developing an app server. The result is usually a
slow to start, memory hogging, beast. We’re not here to create an ultra
flexible, super powerful, infinitely composable, be anything to anyone
platform. We’re here to deliver Java EE 6 Web Profile in the simplest way
possible.

If you were to imagine taking a plain Tomcat install and integrating the
missing components in the most direct and to-the-point style possible,
you’d end up with TomEE. The result speaks for itself:

  • Runs without any additional memory requirements
  • Compatible with most Tomcat-aware tools
  • Compatible with Tomcat-tested apps

History

In Apache TomEE’s previous life, it was simply known as the OpenEJB+Tomcat
integration. That description was always quite misleading. For one,
there’s incredible benefit even if EJB is never used.

Quite simply, EJB as a technology integrates with the most number of specs
than any other spec. It touches JMS, Web Services, Connectors, Servlets
(EJB Web Services are still driven by Servlets!), JPA, JDBC, Transactions,
Security. Integrating with all these technologies takes time and expertise
and in the end has very little to do with EJB specifically. To apply this
all to Tomcat and leverage it all from a simple Servlet is a natural
extension and the reason most app servers started out as EJB servers.

Whereas most app servers pluck Tomcat out of its environment, Apache
OpenEJB has always existed as an embeddable container focused on being as
tiny and invisible as possible. The natural extension of this is to embed
the «EE» into Tomcat, rather than the other way around.

But in the end, it is not about EJB. It’s about the other guys: ActiveMQ,
CXF, MyFaces, OpenJPA, OpenWebBeans, and of course Tomcat! So out with
OpenEJB+Tomcat and in with Apache TomEE!

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 firewall enabled currently.

Tomcat uses port 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 in a web browser:

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:

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 file:

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

tomcat-users.xml — Admin User

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 files.

For the Manager app, type:

For the Host Manager app, type:

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

Save and close the files when you are finished.

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

Using Embedded Tomcat server for a WAR File

Bookstore.war

package net.codejava;

import javax.servlet.ServletException;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

public class RunWarExample {

	public static void main(String[] args) throws ServletException, LifecycleException {
		Tomcat tomcat = new Tomcat();
tomcat.setBaseDir("temp");
		tomcat.setPort(8080);
		
		String contextPath = "/Bookstore";		
		String warFilePath = "D:\\Web\\Website\\Bookstore.war";
		
		tomcat.getHost().setAppBase(".");
		
		tomcat.addWebapp(contextPath, warFilePath);
		
		tomcat.start();
		tomcat.getServer().await();
	}
}

Step 3: Install Tomcat

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

Find the latest version of Tomcat 8 at the Tomcat 8 Downloads page. At the time of writing, the latest version is 8.5.5, 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 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:

Use to download the link that you copied from the Tomcat website:

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

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

Initial configuration

In order to be able to use the manager webapp and the admin webapp you need to edit the following file:

Here is a bare configuration file that declares some of these roles along with usernames and passwords (Be sure to change the following passwords to something secure):

/etc/tomcat7/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <role rolename="admin-gui"/>
  <role rolename="admin-script"/>
  <user username="tomcat" password="" roles="tomcat"/>
  <user username="manager" password="" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
  <user username="admin" password="" roles="admin-gui"/>
</tomcat-users>

Keep in mind that Tomcat must be restarted each time a modification is made to this file.

To have read permissions on the configuration files and work well with some IDEs, you must add your user to the `tomcat7` (respectively `tomcat8`) group:

 gpasswd -a <user> tomcat<number>

Установка Tomcat

На данный момент Tomcat 8 проще всего установить вручную из бинарного релиза.

Загрузка бинарных файлов Tomcat

На странице загрузки найдите последнюю актуальную версию Tomcat. На данный момент такой версией является 8.0.23. В разделе Binary Distributions найдите список Core и скопируйте ссылку на tar.gz.

Загрузите бинарный дистрибутив в домашний каталог. Сначала откройте домашний каталог:

Добавьте ссылку к команде wget, чтобы загрузить архив Tomcat (приведенная ниже ссылка может отличаться):

Установите Tomcat в каталог /opt/tomcat. Создайте этот каталог и извлеките в него архив:

После этого нужно установить соответствующие права на каталог.

Права пользователя tomcat

Пользователь tomcat должен иметь доступ к установке Tomcat.

Откройте каталог Tomcat:

Дайте пользователю tomcat право на изменение каталога conf и право на чтение файлов в нём:

Затем сделайте пользователя tomcat владельцем каталогов work, temp и logs.

Установка Upstart

Чтобы запустить Tomcat как сервис, нужно установить Upstart.

Серверу Tomcat нужно знать, где находится установка Java. Этот путь называется JAVA_HOME. Чтобы узнать местонахождение установки, используйте команду:

Примечание: В данном примере JAVAHOME выделен красным.

Теперь можно приступать к созданию скрипта Upstart. Для этого используйте команду:

Внесите в файл следующий скрипт, при необходимости изменив JAVA_HOME; также можно изменить настройки распределения памяти, которые указаны в CATALINA_OPTS:

Сохраните и закройте файл. Этот скрипт будет запускать сервис Tomcat как пользователя tomcat со всеми указанными настройками.

Теперь нужно обновить настройки Upstart, чтобы использовать новый скрипт для Tomcat:

Теперь сервер Tomcat готов к запуску. Для этого используйте:

Настройка Tomcat еще не завершена, но при необходимости вы можете получить доступ к стандартной проходной странице, открыв в браузере IP-адрес и порт 8080:

На экране появится стандартная проходная страница Tomcat.

6: Работа с веб-интерфейсом Tomcat

Итак, определив администратора сервера, можно открыть интерфейс управления в браузере:

Это откроет домашнюю страницу Tomcat по умолчанию, содержащую сообщение «It works!» и некоторую дополнительную информацию о сервере.

Помимо прочей информации на странице можно найти ссылки на ранее установленные пакеты (раздел 3):

  • tomcat7-docs: онлайн-документация Tomcat; доступна по http://ip_адрес:8080/docs/
  • tomcat7-examples: образцы и примеры Tomcat 7 Servlet и JSP. Этот инструмент позволяет просмотреть примеры веб-приложений (а также посмотреть на их исходный код), чтобы получить общее представление о том, как они работают. Ссылка доступа: http://ip_адрес:8080/examples/
  • tomcat7-admin (manager-webapp): Tomcat Web Application Manager, менеджер веб-приложений Tomcat; он позволяет управлять Java-приложениями.
  • tomcat7-admin (host-manager): Tomcat Virtual Host Manager, менеджер виртуальных хостов Tomcat.

Как видите, этот менеджер способен значительно простить работу с приложениями Java. Он позволяет запустить, отключить, перезапустить, развернуть и свернуть приложение (смотрите столбец Commands), а также выполнить диагностику приложений (то есть, обнаружить утечки памяти). Кроме того, в самом низу этой страницы можно найти информацию о сервере.

Теперь откройте Tomcat Virtual Host Manager при помощи http://ip_адрес:8080/host-manager/html/.

Данный менеджер позволяет добавлять виртуальные хосты для обслуживания веб-приложений.

Готово! Установка сервера приложений Tomcat завершена; можно приступать к развертыванию веб-приложений.

Apache TomcatApache Tomcat 7JavaJava Development KitLinuxOpenJDKUbuntuUbuntu 14.04VPS

Добавление JNDI-ресурса в Apache Tomcat

Закачиваем его на сервер с помощью PuTTY:

pscp.exe postgresql-9.4-1201.jdbc41.jar root@<IP_сервера>:/root

1 pscp.exe postgresql-9.4-1201.jdbc41.jarroot@<IP_сервера>root

На сервере перемещаем его из каталога /root в каталог /opt/apache-tomcat-8.0.24/lib:

mv /root/postgresql-9.4-1201.jdbc41.jar /opt/apache-tomcat-8.0.24/lib/

1 mv /root/postgresql-9.4-1201.jdbc41.jar /opt/apache-tomcat-8.0.24/lib/

Открываем на редактирование файл /opt/apache-tomcat-8.0.24/conf/context.xml и дописываем там JNDI-ресурс:

<Resource name=»jdbc/tomcatDB»
auth=»Container»
type=»javax.sql.DataSource»
username=»tomcat»
password=»newuserpassword»
driverClassName=»org.postgresql.Driver»
url=»jdbc:postgresql://localhost:5432/tomcat»
maxTotal=»8″
maxIdle=»4″/>

1
2
3
4
5
6
7
8
9

<Resource name=»jdbc/tomcatDB»
            auth=»Container»
            type=»javax.sql.DataSource»
            username=»tomcat»
            password=»newuserpassword»
            driverClassName=»org.postgresql.Driver»
            url=»jdbc:postgresql://localhost:5432/tomcat»
            maxTotal=»8″
            maxIdle=»4″/>

Эти строчки нужно добавлять внутри тега Context.

Теперь JNDI-ресурс настроен. Для проверки можно остановить сервер и запустить снова. В логе не должно быть ошибок. Можно деплоить war-файлы. Для этого их нужно поместить в каталог /opt/apache-tomcat-8.0.24/webapps и Apache Tomcat сам их развернёт и запустит.

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:

The correct variable can be constructed by taking the output from the last column (highlighted in red) and appending to the end. Given the example above, the correct for this server would be:

Your may be different.

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

Paste the following contents into your service file. Modify the value of 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 :

/etc/systemd/system/tomcat.service

When you are finished, save and close the file.

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

Start the Tomcat service by typing:

Double check that it started without errors by typing:

Installing / Updating to the Latest Java 8 Version

In order to install the binaries we’re going to SSH into the server as root and use GNU Wget to download the dependencies. I’m installing Java to /usr/local but if you want you can substitute for another location such as /opt or /usr/share. Note that when you see a command-line with a hash sign at the beginning this is a unix standard indicating that you are logged in ‘as the root user.’ However, if you are not logged in as root, all of the commands displaying a hash sign, will require ‘sudo’ permissions. Respectively a dollar sign indicates you are a normal user. For more about the command and running as root you can checkout the man pages or the CentOS Wiki.

So let’s into your target directory as root and grab the latest java version…

cd /usr/local/ && wget --no-check-certificate -c \
--header "Cookie: oraclelicense=accept-securebackup-cookie" \
http://download.oracle.com/otn-pub/java/jdk/8u45-b14/jdk-8u45-linux-x64.tar.gz

After the archive downloads it may have been saved with the query string AuthParam appended. If so just rename the archive so it ends with a extension.

ls -l | grep jdk

mv jdk-8u45-linux-x64.tar.gz\?AuthParam\=1429150407_03533c0686909067456bf8c408ad56c9 jdk-8u45-linux-x64.tar.gz

Next we need to extract the archive into the target directory using tar. Again, if you’re not installing into update your paths accordingly.

tar xvzf jdk-8u45-linux-x64.tar.gz
ln -s /opt/apache-tomcat-8.0.21 tomcat

To make future JDK updates easier, I like to create a Symlink  referencing the current JDK so all the Java binaries are automatically repointed to the current JDK via the Linux Alternatives  binary version manager. Below I’m simply making the symlink reference the newly extracted JDK.

ln -s /usr/local/jdk1.8.0_45 jdk

This next series of commands isn’t strictly required. However, if you don’t currently have Java installed on your system it sure makes future updates easier so I recommend just following along so all you have to do is swap out the JDK symlink next time you update your JDK. If however you need to update the Java version, the Alternatives How-To on the CentOS wiki can get you up to speed pretty quick on the task.

Assuming you don’t have alternatives setup for Java, the next commands will install the alternatives links for the JDK binaries.

update-alternatives --install /usr/bin/java java /usr/local/jdk/bin/java 1
update-alternatives --install /usr/bin/javac javac /usr/local/jdk/bin/javac 1
update-alternatives --install /usr/bin/javaws javaws /usr/local/jdk/bin/javaws 1

Once you’ve issued those commands you can verify the versions by passing the argument to the alternatives system.

update-alternatives --display java
update-alternatives --display javac
update-alternatives --display javaws

After you’ve installed and confirmed the alternatives simply issue to confirm the system is finding the JDK.

java -version

If you’ve made it this far Congratulations! You’re halfway to having a production Java server, but don’t celebrate just yet, installing the JDK was easy, now we have to install and configure Tomcat.

Шаг 3 — Установка Tomcat

Лучшим способом установки Tomcat 9 является загрузка последней бинарной версии, а затем ее ручная настройка.

Далее перейдите к директории на сервере. Эта директория отлично подходит для загрузки кратковременных элементов, таких как tar-архив (тарбол) Tomcat, который нам не потребуется после извлечения содержимого Tomcat:

Используйте для загрузки ссылки, скопированной на веб-сайте Tomcat:

Мы установим Tomcat в директорию . Создайте директорию, а затем извлеките туда архив с помощью этих команд:

Далее мы сможем настроить соответствующие разрешения пользователя для нашей установки.

Заключение

Ваша установка Tomcat завершена! Теперь вы можете развернуть ваши собственные веб-приложения Java!

В настоящее время ваша установка Tomcat работает, но абсолютно не имеет шифрования. Это означает, что все данные, включая чувствительную информацию, например пароли, отправляются в текстовой форме и могут быть кем-либо перехвачены и прочитаны в Интернете. Чтобы предотвратить это, мы настоятельно рекомендуем шифровать ваши соединения с помощью SSL. Вы можете узнать, как реализовать шифрование ваших подключений в Tomcat в этом руководстве (примечание: в настоящем руководстве описано шифрование Tomcat 8 в Ubuntu 16.04).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *