Как перезапустить tomcat linux
Установка и базовая настройка Tomcat на Linux Ubuntu Server
Tomcat на Ubuntu не устанавливается из репозитория (в отличие от некоторых других дистрибутивов Linux, например, CentOS). Поэтому в данной инструкции мы выполним ручную установку — развертывание дополнительных компонентов (Java), загрузку и распаковку пакета веб-сервера Tomcat, а также настройку его автоматического запуска в случае сбоя или после перезагрузки системы. На момент обновления инструкции использовался Tomcat версии 10 и Ubuntu 20.04.
Подготовка системы
Обновляем список пакетов в репозиториях:
Задаем имя серверу:
hostnamectl set-hostname server.dmosk.ru
* в данном примере мы зададим имя server.dmosk.ru.
Настраиваем часовой пояс, например:
timedatectl set-timezone Europe/Moscow
* где Europe/Moscow — московское время. Список всех возможных зон смотрим командой timedatectl list-timezones.
Устанавливаем сервис для автоматической синхронизации времени, а также разрешаем его автозапуск:
apt-get install chrony
systemctl enable chrony
Если мы используем брандмауэр, необходимо открыть порт 8080:
* 8080 — порт по умолчанию, на котором работает Tomcat. Если мы заходим поменять данный порт, то нужно будет открыть именно его.
Сохраняем правила — для этого устанавливаем утилиту iptables-persistent:
apt-get install iptables-persistent
Если в процессе установки мы отказались сохранять правила, выполняем команду:
Можно приступать к установке Java.
Подготовка к установке
Для работы веб-сервера нам необходимы Java и пользователь, под которым будет работать Tomcat.
Установка JAVA
Мы установим пакет openjdk. Для этого вводим команду:
apt-get install default-jdk
* будет установлена последняя версия, максимально совместимая с используемой версией операционной системы Ubuntu.
Если в системе окажется несколько версий java, выберем последнюю. Для этого вводим команду:
. и выбираем в списке соответствующий вариант.
Проверяем используемую версию java:
Мы должны увидеть что-то на подобие:
openjdk version «14.0.2» 2020-07-14
OpenJDK Runtime Environment (build 14.0.2+12-Ubuntu-120.04)
OpenJDK 64-Bit Server VM (build 14.0.2+12-Ubuntu-120.04, mixed mode, sharing)
Создание пользователя
Создаем пользователя командой:
* в итоге будет создан пользователь tomcat со следующими опциями:
Можно приступать к установке веб-сервера Apache Tomcat.
Установка Tomcat
Переходим на страницу официального сайта веб-сервера. В меню слева выбираем необходимую версию Tomcat:
* на момент обновления статьи, последняя версия была 10.
Копируем ссылку на архив tar.gz:
Используя скопированную ссылку, скачиваем архив на наш сервер:
Распаковываем содержимое архива в каталог /opt/tomcat:
Готово. Можно запустить сервер командой:
Открываем браузер и переходим на страницу http:// :8080 — мы должны увидеть стартовую страницу Tomcat:
Наш сервер работает.
Посмотреть версию установленного программного обеспечения можно командой:
Мы должны увидеть что-то на подобие:
Server version: Apache Tomcat/10.0.2
Server built: Jan 28 2021 18:48:46 UTC
Server number: 10.0.2.0
OS Name: Linux
OS Version: 5.4.0-26-generic
Architecture: amd64
JVM Version: 14.0.2+12-Ubuntu-120.04
JVM Vendor: Private Build
Настройка автозапуска
Мы выполнили разовый запуск нашего веб-сервера, но, когда будет перезагружен компьютер, он не запустится. Чтобы это исправить, мы создадим юнит в systemd.
Для начала, остановим работу Tomcat:
Поменяем владельца для всех файлов в каталоге /opt/tomcat:
Создадим конфигурационный файл для нового юнита:
[Unit]
Description=Apache Tomcat Server
After=network.target
* где обращаем внимание на:
Из данных опций, возможно вам захочется поменять CATALINA_OPTS, например, задать другие значения для выделения памяти или указать определенный порт. Остальные опции можно оставить.
Перечитываем новый конфигурационный файл в systemd:
linux-notes.org
Apache Tomcat (ранее — Catalina) — это контейнер сервлетов с открытым исходным кодом, разрабатываемый Apache Software Foundation. Реализует спецификацию сервлетов и спецификацию JavaServer Pages (JSP) и JavaServer Faces (JSF). Написан на языке Java. Томкат дает возможность запускать приложения для веба, которые содержат ряд утилит для самоконфигурирования.
Tomcat используется в качестве самостоятельного веб-сервера, в качестве сервера контента в сочетании с веб-сервером Apache HTTP Server, а также в качестве контейнера сервлетов в серверах приложений JBoss и GlassFish.
Установка Tomcat в Unix/Linux
Я стараюсь писать статьи со всем необходимым и чтобы снизить поиски траблошутов в интернете. Я расскажу как установить, настроить и работать с Apache Tomcat в различных Unix/Linux ОС.
Но перед тем как приступим к самой установке, проверяем, установлена ли JAVA на сервере и какая версия:
Если java не установлена в системе, то приступим к установке:
Для других Unix/Linux ОС мне не приходилось устанавливать. По мере возможности, я буду дополнять данный материал новой информацией.
PS: На момент написания статьи, самая актуальная версия — java8 ( 1.8).
Создание пользователя
В идеале, необходимо создать нового пользователя для запуска Tomcat. В этом примере я создам non-login пользователя «tomcat:
Установка Tomcat в Debian/Ubuntu/CentOS/Fedora/RedHat/Gentoo/Arch
Я описывал в своей статье, процесс установки tomcat для Ubuntu:
Установка для любого Unix/Linux примитивная — идем на официальный сайт и качаем новую версию томката. Я заюзаю самую последнюю ( но учитывайте дату написания статьи):
Старый архив удаляем:
Для удобства, переименуем данный томкат:
Меняем права на папку, для того чтобы новый пользователь (tomcat, которого создали в самом начале статьи) мог запустить Tomcat:
Я например, делал вот так:
Но это не удобно, немного ниже я расскажу как можно оптимизировать.
Установка Tomcat в Mac OS X
Для начала подключаем brew:
Выполним поиск пакета:
У меня имеется следующие версии:
Для установки используйте:
PS: Настройку я не выполнял, по этому — я пока-что упущу данную тему.
Установка Tomcat на другие Unix/Linux ОС
Для других Unix/Linux ОС, можно заюзать docker. Я мало где юзаю его, по этому — пока что нет данной инфы по установке. Но я надеюсь что я выложу.
Настройка Tomcat в Unix/Linux
И так, хотелось бы рассказать как можно запускать томкат. Но для начала, нужно узнать какой механизм инициализации используется:
PS: Вот довольно полезное чтиво:
Запуск TOMCAT с SysV init
Создадим init скрипт для запуска:
Даем права на запуск ( на исполнение):
Добавляем службу в автозагрузку:
Открываем браузер и смотрим что вышло!
PS: По дефолту, нужно открыть URL-у на 8080-м порту. Я внизу статьи, расскажу как можно будет настроить томкат.
Вот полезное чтиво о том, как создавать SysV init файлы в Unix/Linux:
БУДЕТ, немного позже!
Запуск TOMCAT с systemd
И приводим к подобному виду:
Чтобы созданный файл применился, перезагрузим службу:
Чтобы добавить томкат в автозагрузку ОС, выполните:
Чтобы проверить статус, выполняем:
Как видим, все четко работает.
Вот полезное чтиво о том, как создавать SystemD unit файлы в Unix/Linux:
Изменить порт в tomcat
и меняем его, после чего — выполняем рестарт томката.
Создание виртуального хоста для tomcat
Виртуальный хостинг предоставляет нам возможность размещать несколько доменов (веб-сайтов) на одном сервере.
Я для примера, создал домен и повесил его на 192.168.1.100. Веб-апликейшены работают на tomcat 9 и исползуют 80-й порт. Я добавил 2 java-приложения через панель — Tomcat Admin. Теперь оба приложения работают по следующим URL-м:
Теперь мы хотим запускать оба веб-приложения на основных доменах (tomcat1.linux-notes.org и tomcat2.linux-notes.org). Таким образом, конечные пользователи могут получить доступ к веб-приложению, используя доменное имя.
И так, открываем файл:
Суть надеюсь понятна и проста.
После чего, стоит выполнить перезагрузку томката. Я не буду повторятся как это делать, я описывал это в верху.
Настройка SSL для Tomcat
Знаю как, но пока-что не делал.
Безопасность Tomcat в Linux
Нужно упомянуть про несколько очень важных моментов по безопасности при работе с Tomcat. Рассмотренные выше «ручные» варианты подразумевают обычно запуск из-под root-пользователя. В результате, если вы ещё и стандартно в файле, задающем пользователей (/usr/local/tomcat9/conf/tomcat-users.xml) раскомментируете блок оных:
…или воспользуетесь распространёнными в интернете примерами получения админских прав типа:
Как-то так, статья «Установка Tomcat в Unix/Linux » завершена.
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.
Tomcat: The Definitive Guide, 2nd Edition by
Get full access to Tomcat: The Definitive Guide, 2nd Edition and 60K+ other titles, with free 10-day trial of O’Reilly.
There’s also live online events, interactive content, certification prep materials, and more.
Starting, Stopping, and Restarting Tomcat
Once you have the installation completed, you will probably be eager to start Tomcat and see if it works. This section details how to start up and shut down Tomcat, including specific information on each supported operating system. It also details common errors that you may encounter, enabling you to quickly identify and resolve any problems you run into.
Starting Up and Shutting Down
Table 1-1. Tomcat invocation scripts
The main Tomcat script. This runs the java command to invoke the Tomcat startup and shutdown classes.
This is used internally, and then only on Windows systems, to append items to Tomcat classpath environment variables.
This makes a crypto digest of Tomcat passwords. Use it to generate encrypted passwords.
This script installs and uninstalls Tomcat as a Windows service.
This is also only used internally and sets the Tomcat classpath and several other environment variables.
This runs catalina stop and shuts down Tomcat.
This runs catalina start and starts up Tomcat.
This is a generic Tomcat command-line tool wrapper script that can be used to set environment variables and then call the main method of any fully qualified class that is in the classpath that is set. This is used internally by the digest script.
This runs the catalina version, which outputs Tomcat’s version information.
Example 1-1. Output from catalina run
Table 1-2. Startup options
-config [ server.xml file]
This prints out a summary of the command-line options.
This disables the use of JNDI within Tomcat.
This enables the use of the catalina.policy file.
This starts Tomcat in debugging mode.
This allows Tomcat to be tested in an embedded mode, and is usually used by application server developers.
This starts Tomcat as a Java Platform Debugger Architecture-compliant debugger. See Sun’s JPDA documentation at http://java.sun.com/products/jpda.
This starts up Tomcat without redirecting the standard output and errors.
This starts up Tomcat, with standard output and errors going to the Tomcat logfiles.
This outputs Tomcat’s version information.
Environment variables
To prevent runaway programs from overwhelming the operating system, Java runtime environments feature limits such as «maximum heap size.» These limits were established when memory was more expensive than at present; for JDK 1.3, for example, the default limit was only 32 MB. However, there are options supplied to the java command that let you control the limits. The exact form depends upon the Java runtime, but if you are using the Sun runtime, you can enter:
This will run a class file called MyProg with a maximum memory size of 256 MB for the entire Java runtime process.
These options become important when using Tomcat, as running servlets can begin to take up a lot of memory in your Java environment. To pass this or any other option into the java command that is used to start Tomcat, you can set the option in the environment variable JAVA_OPTS before running one of the Tomcat startup scripts.
Windows users should set this environment variable from the Control Panel, and Unix users should set it directly in a shell prompt or login script:
Other Tomcat environment variables you can set are listed in Table 1-3.
Table 1-3. Tomcat environment variables
Tomcat installation directory
This sets the base directory for static (read-only) portions of Tomcat, such as Tomcat’s lib directories and command-line scripts.
Tomcat installation directory
This passes through Tomcat-specific command-line options to the java command.
This sets the directory for Tomcat temporary files.
This sets the location of the Java runtime or JDK that Tomcat will use.
This is an alias to JAVA_HOME.
This is where you may set any Java command-line options.
This variable may set the transport protocol used for JPDA debugging.
This sets the address for the JPDA used with the catalina jpda start command.
This sets the location of the Java Secure Sockets Extension used with HTTPS.
This variable may optionally hold the path to the process ID file that Tomcat should use when starting up and shutting down.
Starting and stopping: The general case
Make sure you’re not running a TCP server on port 8080 (the default Tomcat HTTP server socket port), nor on TCP port 8005 (the default Tomcat shutdown server socket port). Try running telnet localhost 8080 and telnet localhost 8005 to see if any existing server accepts a connection, just to be sure.
Start up Tomcat with its startup.sh script like this:
You should see output similar to this when Tomcat starts up. Once started, it should be able to serve web pages on port 8080 (if the server is localhost, try http://localhost:8080 in your web browser).
Invoke the shutdown.sh script to shut Tomcat down:
Starting and stopping on Linux
If you’ve installed Tomcat via the RPM package on Linux, you can test it out by issuing a start command via Tomcat’s init script, like this:
Or, on some Linux distributions, such as Fedora and Red Hat, to do the same thing, you may instead type the shorter command:
Then, check to see if it’s running:
You should see several Java processes scroll by. Another way to see whether Tomcat is running is to request a web page from the server over TCP port 8080.
If Tomcat fails to startup correctly, go back and make sure that the /opt/tomcat/conf/tomcat-env.sh file has all the right settings for your server computer (in the JPackage.org RPM installation case, it’s the /etc/tomcat55/tomcat55.conf file). Also check out the «Common Errors» section, later in this chapter.
To stop Tomcat, issue a stop command like this:
Starting and stopping on Solaris
To use Tomcat’s init script on Solaris, you must be the root user. Switch to root first. Then, you can start Tomcat like this:
And, you can stop it like this:
Watch your catalina.out logfile in /opt/csw/share/tomcat5/logs so that you’ll know if there are any errors.
Starting and stopping on Windows
On Microsoft Windows, Tomcat can be started and stopped either as a windows service or by running a batch file. If you arrange for automatic startup (detailed later in this chapter), you may manually start Tomcat in the control panel. If not, you can start Tomcat from the desktop icon.
If you have Tomcat running in a console window, you can interrupt it (usually with Ctrl-C) and it will catch the signal and shut down:
If the graceful shutdown does not work, you need to find the running process and terminate it. The JVM running Tomcat will usually be identified as a Java process; be sure you get the correct Java if other people or systems may be using Java. Use Ctrl-Alt-Delete to get to the task manager, select the correct Java process, and click on End Task.
Starting and stopping on Mac OS X
The Mac OS X installation of Tomcat is simply the binary distribution, which means you can use the packaged shell scripts that come with the Apache binary release. This provides a quick and easy set of scripts to start and stop Tomcat as required. First, we will show you the general case for starting and stopping Tomcat on Mac OS X.
Mac OS X sets all your paths for you so all you need to do is ensure that there are no TCP services already running on port 8080 (the default Tomcat HTTP server socket port), nor on port 8005 (the default Tomcat shutdown port). This can be done easily by running the netstat command:
You should see no output. If you do, it means another program is listening on port 8080, and you should shut it down first, or you must change the port numbers in your CATALINA_HOME/conf/server.xml configuration file. Do the same for port 8005.
Tomcat can be started on OS X with the following command:
Tomcat can be stopped with the following command:
Starting and stopping on FreeBSD
Try starting Tomcat like this:
This will only work if you have added this line to your /etc/rc.conf file:
You may use the tomcat60.sh script to start, stop, and restart Tomcat 6.
By default, this FreeBSD port of Tomcat 6.0 sets Tomcat’s default HTTP port to be 8180, which is different than the default that is originally set (for all operating systems) in the Apache Software Foundation’s distribution of Tomcat (which is 8080). Try accessing your FreeBSD Tomcat port via the URL http://localhost:8180/.
Common Errors
Several common problems can result when you try to start up Tomcat. While there are many more errors that you can run into, these are the ones we most often encounter.
Ensure that you don’t have Tomcat already started. If you don’t, check to see if other programs, such as another Java application server or Apache Web Server, are running on these ports.
Another instance of Tomcat is running
Remember that not only must the HTTP port of different Tomcat instances (JVMs) be different, every port number in the Server and Connector elements in the server.xml files must be different between instances. For more information on these elements, consult Chapter 7.
Restarting Tomcat
The Java Servlet Specification does not mandate any time limit for how long a Java servlet may take to perform its work. Writing a servlet that takes forever to perform its work does not break compliance with the Java Servlet Specification, but it can prevent Tomcat from shutting down.
The Java Servlet Specification also dictates that on shutdowns, servlet containers must wait for each servlet to finish serving all requests that are in progress before taking the servlet out of service, or wait a container-specific timeout duration before taking servlets out of service. For Tomcat 6, that timeout duration is a maximum of a half-second per servlet. When a servlet misbehaves and takes too long to finish serving requests, it’s up to Tomcat to figure out that the servlet has taken too long and forcibly take it out of service so that Tomcat can shut down. This processing takes time, though, and slows Tomcat’s own shutdown processing.
Multithreading in Java virtual machines is specified in a way that means that Java code will not always be able to tell exactly how much real time is going by (Java SE is not a real-time programming environment). Also, due to the way Java threads are scheduled on the CPU, threads can become blocked and stay blocked. Because of these limitations, the Java code that is called on invocations of shutdown.sh will not always know how long to wait for Tomcat to shut down, nor can Tomcat always know it’s taking too long to shut down. That means that shutdowns are not completely reliable when written in pure Java. An external program would need to be written in some other programming language to reliably shut down Tomcat.
Because Tomcat is an embeddable servlet container, it tries not to call System.exit(0) when shutting down the server because Tomcat does not know what else may need to stay running in the same Java virtual machine. Instead, Tomcat shuts down all of its own threads so that the VM can exit gracefully if nothing else needs to run. Because of that, a servlet could spawn a thread that would keep the VM from exiting even when Tomcat’s threads are all shut down.
The Java Servlet Specification allows servlets to create additional Java threads that perform work as long as any security manager allows it. [4] Once another thread is spawned from a servlet, it can raise its own priority higher than Tomcat’s threads’ priorities (if the security manager allows) and could keep Tomcat from shutting down or from running at all. Usually if this happens, it’s not malicious code but buggy code. Try not to do this!
If your Tomcat instance has run completely out of memory (as evidenced by the dreaded «Permgen memory» error in the logs), it will usually be unable to accept new connections on its web port or on its shutdown port.
To fix some of the problems, you may want to configure and use a security manager. See Chapter 6 for more information on how to place limits on webapps to guard against some of these problems.
The general case
Change directory into the root of the Tomcat installation directory (commonly known as the CATALINA_HOME directory):
Issue a shutdown via the shutdown.sh script:
Decide how long you want to wait for Tomcat to shut down gracefully, and wait that period of time. Reasonable maximum shutdown durations depend on your web application, your server computer’s hardware, and how busy your server computer is, but in practice, Tomcat often takes several seconds to completely shut down.
Query your operating system for java processes to make sure it shut down. On Windows, hit Ctrl-Alt-Delete to get to the task manager, and scroll through the list to look for it. On all other operating systems, use the j ps command to look for any remaining Tomcat processes that are your Tomcat’s Java virtual machine. The jps command comes with Java. Try this:
If that fails, use an OS-dependent Process Status (ps) command, such as this:
If no Tomcat java processes are running, skip to step 6. Otherwise, because the Tomcat JVM is not shutting down in the time you’ve allowed, you may want to force it to exit. Send a TERM signal to the processes you find, asking the JVM to perform a shutdown (ensuring you have the correct user permissions):
Do another ps like you did in step 4. If the Tomcat JVM processes remain, repeat step 5 until they’re gone. If they persist, have your operating system kill the java process. On Windows, use the task manager to end the task(s). On all other operating systems, use the kill command to tell the kernel to kill the process(es) like this:
Once you’re sure that Tomcat’s JVM is no longer running, start a new Tomcat process:
Usually, the shutdown process goes smoothly and Tomcat JVMs shut down quickly. But, because there are situations when they don’t, the above procedure should always suffice. We realize this is not a very convenient way to restart Tomcat; however, if you try to cut corners here, you will likely not always shut down Tomcat and get errors due to the new Tomcat JVM bumping into the existing Tomcat JVM when you go to start it again. Luckily, for most operating systems, there are scripts that automate this entire procedure, implemented as a «restart» command. You’ll find these integrated into most OS-specific Tomcat installation packages (Linux RPM packages, the FreeBSD port, etc.).
Restarting Tomcat on Linux
The following outlines how to reliably restart Tomcat on Linux. If you have installed Tomcat via an RPM package, either the one from this book or the one from JPackage.org, restarting Tomcat is easy. If you installed the RPM package from this book, do:
And, if you installed the JPackage.org RPM package, do:
which should reliably restart Tomcat. Be sure to check your logfiles for any startup problems.
Restarting Tomcat on Solaris
The following outlines how to reliably restart Tomcat on Solaris. If you have installed Tomcat via a Blastwave Solaris CSW package, restarting Tomcat is easy:
That should restart Tomcat. Be sure to check your logfiles for any startup problems.
As of this writing, the Blastwave package’s init script does not contain any code to reliably restart Tomcat—it does not watch the processes to make sure that they came down all the way, nor does it try to force the processes down if they do not come down on their own. Read the init script source and you’ll see what we mean. So, it is up to the Solaris administrator to ensure (by hand) that the restart actually occurred.
Restarting the Tomcat Windows Service
If you have Tomcat running as a Windows Service, you can restart it from the control panel. Either right-click on the service and select Restart from the pop-up menu or, if it exists on your version of Windows, use the Restart button near the upper-right corner of the dialog box (see Figure 1-6).
Figure 1-6. Restart button in Control Panel
Be sure to check your logfiles for any startup problems.
Restarting Tomcat on Mac OS X
The standard way to restart Tomcat on OS X is to stop and then start Tomcat.
A simple way to see if Tomcat is running is to check if there is a service listening on TCP port 8080 with the netstat command. This will, of course, only work if you are running Tomcat on the port you specify (its default port of 8080, for example) and not running any other service on that port.
First, shut down the currently running Tomcat instance:
Then, check to make sure Tomcat is no longer running:
You should see no output, meaning that Tomcat has shut down. Then, you may start it back up again, like this:
After waiting some seconds, check to make sure that Tomcat is running and listening on port 8080 again:
If you have chosen to use the automatic startup and shutdown scripts for Tomcat via Apple’s launchd (see the section «Automatic Startup on Mac OS X,» later in this chapter, for details about how to set that up), it’s very easy to restart Tomcat simply by unloading the service and reloading it into launchd :
Restarting Tomcat on FreeBSD
The following outlines how to reliably restart Tomcat on FreeBSD. You can restart the Tomcat 6 port by running:
That should reliably restart Tomcat. Be sure to check your logfiles for any startup problems.
[4] * An urban legend about developing Java webapps says that according to the Java Servlet Specification, servlets in webapps are not allowed to spawn any Java threads. That is false. The servlet specification does not preclude doing this, so it is OK to spawn one or more threads as long as the thread(s) are well behaved. This is often the rub, since webapp developers often report bugs against Tomcat that turn out to be caused by their own code running in a separate thread.
Get Tomcat: The Definitive Guide, 2nd Edition now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.