tomcat – коротко для windows
С сайта http://tomcat.apache.org сохраняем zip-архив, и распаковываем его в папку с путём без пробелов и всяких сложных символов, например, «E:\tomcat\apache-tomcat-8.0.15».
Скачиваем последнюю версию JDK с сайта оракл https://www.oracle.com и ставим её тоже в папку с названием без пробелов (если так не сделать, и установить в папку X:\Program Files\. , то затем, когда мы будем править батник, нам придётся неявно указывать имя папки, это не очень хорошо, почему- будет видно дальше.
Открываем «e:\tomcat\apache-tomcat-8.0.15\bin\». Видим много батников и sh сценариев.
Открываем «catalina.bat». Там видим много закомментированных строк с переменными окружения, которые должны быть объявлены, или которые можно объявлять, а можно и нет.
Те переменные, которые должны быть объявлены — это
- set CATALINA_HOME=»e:\tomcat\apache-tomcat-8.0.15″
- set JAVA_HOME=»e:\ProgramFiles\Java\jre1.8.0_25″
причём желательно это сделать в отдельном файле с именем setenv.bat, для этого просто в текстовом редакторе вбиваем эти две строки и сохраняем файл с таким именем в «e:\tomcat\apache-tomcat-8.0.15\bin\»
Примечание: если папка с установленным jre содержит пробелы, то имя должно состоять из максимум шести первых букв реального названия папки, и если такое сочетание по алфавиту в диске первое, то
1, если второе, то
Например, название папки, внутри которой находится jre, “C:\Program Files\JRE”, а кроме того есть папка «C:\places\», тогда вторая строчка в setenv.bat будет
1\Java\jre1.8.0_25″, или
set JAVA_HOME=»e:\P
Естественно, это не очень хорошо, особенно когда у вас две папки “Program Files” и «Program Files (x86)». В таком случае, чтобы проименовать правильно папку с JRE, придётся поэкспериментировать
Пробуем запустить, для этого из текущей директории запускаем cmd.exe, в нём запускаем startup.bat . Это нам даст контроль над тем что происходит. Если всё пошло хорошо, то запустится окно Java-приложения в режиме консоли, в котором после запуска будет написано время старта, если же что-то пошло не так, например, папки в setenv.bat указаны неверно, мы увидим сообщения об ошибках.
Если глобальные переменные сконфигурированы верно, и запустилось окно java – консоли, но какие-то настройки сделаны неверно, то ошибки можно посмотреть в папке «e:\tomcat\apache-tomcat-8.0.15\logs\».
Если пункт 4 выполнен полностью успешно, то в окне браузера можно набрать 127.0.0.1:8080 и в окне будет окно tomcat сервера.
Но если мы захотим войти в настройки Host Manager, и т. д., то нас попросят ввыести логин и пароль. Взять их негде, но в папке conf есть файл tomcat-users.xml, который, если открыть, то сначала кажется правильным, но роли и пользователи там взяты в комментарий . Да и роли, и пользователи там явно неверные. Итак, что же делать.
Для ответа на вопрос, какие роли должны быть, и каких пользоватей назначать, чтобы войти в админку, на страничке 127.0.0.1:8080. Например, про роли manager можно узнать на страничке ttp://127.0.0.1:8080/docs/manager-howto.html, и вместо одного пользователя admin, как было раньше, теперь есть два пользователя: admin-gui и admin-script.
Более подробно про работу с паролями здесь http://127.0.0.1:8080/docs/realm-howto.html
Итак, открываем файл conf\tomcat-user.xml и добавляем там после закомментированного блока с логинами и паролями
Таким образом, мы получим пользователя superadmin с паролем pass.
Tеперь при помощи скриптов shutdown.bat и startup.bat перезапускаем сервер, и можем войти в админку.
можно ещё создать в админке ссылку на хост (Это то же самое, что мы сейчас сделали).
При создании новых записей в hosts для win8, сначала копируем файл в другую папку, там правим, и затем пишем обратно. После этого рестарт компьютера или сервера не нужен.
Apache Tomcat 6.0
Links
User Guide
Reference
Apache Tomcat Development
Apache Tomcat 6.0
Tomcat Setup
There are several ways to set up Tomcat for running on different platforms. The main documentation for this is a file called RUNNING.txt. We encourage you to refer to that file if the information below does not answer some of your questions.
Installing Tomcat on Windows can be done easily using the Windows installer. Its interface and functionality is similar to other wizard based installers, with only a few items of interest.
- Installation as a service: Tomcat will be installed as a Windows service no matter what setting is selected. Using the checkbox on the component page sets the service as «auto» startup, so that Tomcat is automatically started when Windows starts. For optimal security, the service should be run as a separate user, with reduced permissions (see the Windows Services administration tool and its documentation).
- Java location: The installer will provide a default JRE to use to run the service. The installer uses the registry to determine the base path of a Java 5 or later JRE, including the JRE installed as part of the full JDK. When running on a 64-bit operating system, the installer will first look for a 64-bit JRE and only look for a 32-bit JRE if a 64-bit JRE is not found. It is not mandatory to use the default JRE detected by the installer. Any installed Java 5 or later JRE (32-bit or 64-bit) may be used.
- Tray icon: When Tomcat is run as a service, there will not be any tray icon present when Tomcat is running. Note that when choosing to run Tomcat at the end of installation, the tray icon will be used even if Tomcat was installed as a service.
- Refer to the Windows Service HOW-TO for information on how to manage Tomcat as a Windows service.
The installer will create shortcuts allowing starting and configuring Tomcat. It is important to note that the Tomcat administration web application can only be used when Tomcat is running.
Tomcat can be run as a daemon using the jsvc tool from the commons-daemon project. Source tarballs for jsvc are included with the Tomcat binaries, and need to be compiled. Building jsvc requires a C ANSI compiler (such as GCC), GNU Autoconf, and a JDK.
Before running the script, the JAVA_HOME environment variable should be set to the base path of the JDK. Alternately, when calling the ./configure script, the path of the JDK may be specified using the —with-java parameter, such as ./configure —with-java=/usr/java .
Using the following commands should result in a compiled jsvc binary, located in the $CATALINA_HOME/bin folder. This assumes that GNU TAR is used, and that CATALINA_HOME is an environment variable pointing to the base path of the Tomcat installation.
Please note that you should use the GNU make (gmake) instead of the native BSD make on FreeBSD systems.
Tomcat can then be run as a daemon using the following commands.
jsvc has other useful parameters, such as -user which causes it to switch to another user after the daemon initialization is complete. This allows, for example, running Tomcat as a non privileged user while still being able to use privileged ports. jsvc —help will return the full jsvc usage information. In particular, the -debug option is useful to debug issues running jsvc.
Apache Tomcat 6.0
Links
User Guide
Reference
Apache Tomcat Development
Apache Tomcat 6.0
Windows service HOW-TO
Tomcat6 is a service application for running Tomcat 6 as a Windows service.
Tomcat6w is a GUI application for monitoring and configuring Tomcat services.
The available command line options are:
//ES// | Edit service configuration | This is the default operation. It is called if the no option is provided but the executable is renamed to servicenameW.exe |
//MS// | Monitor service | Put the icon in the system tray |
Each command line directive is in the form of //XX//ServiceName
The available command line options are:
//TS// | Run the service as console application | This is the default operation. It is called if the no option is provided. The ServiceName is the name of the executable without exe suffix, meaning Tomcat6 |
//RS// | Run the service | Called only from ServiceManager |
//SS// | Stop the service | |
//US// | Update service parameters | |
//IS// | Install service | |
//DS// | Delete service | Stops the service if running |
Each command parameter is prefixed with —. If the command line is prefixed with ++ then it’s value will be appended to the existing option. If the environment variable with the same name as command line parameter but prefixed with PR_ exists it will take precedence. For example:
is equivalent to providing
as command line parameter.
ParameterName | Default | Description |
---|---|---|
—Description | Service name description (maximum 1024 characters) | |
—DisplayName | ServiceName | Service display name |
—Install | procrun.exe //RS//ServiceName | Install image |
—Startup | manual | Service startup mode can be either auto or manual |
++DependsOn | List of services that this service depend on. Dependent services are separated using either # or ; characters | |
++Environment | List of environment variables that will be provided to the service in the form key=value. They are separated using either # or ; characters. If you need to use either the # or ; character within a value then the entire value must be enclosed inside single quotes. | |
—User | User account used for running executable. It is used only for StartMode java or exe and enables running applications as service under account without LogonAsService privilege. | |
—Password | Password for user account set by —User parameter | |
—JavaHome | JAVA_HOME | Set a different JAVA_HOME than defined by JAVA_HOME environment variable |
—Jvm | auto | Use either auto (i.e. find the JVM from the Windows registry) or specify the full path to the jvm.dll. You can use the environment variable expansion here. |
++JvmOptions | -Xrs | List of options in the form of -D or -X that will be passed to the JVM. The options are separated using either # or ; characters. (Not used in exe mode.) |
—Classpath | Set the Java classpath. (Not used in exe mode.) | |
—JvmMs | Initial memory pool size in MB. (Not used in exe mode.) | |
—JvmMx | Maximum memory pool size in MB. (Not used in exe mode.) | |
—JvmSs | Thread stack size in KB. (Not used in exe mode.) | |
—StartMode | One of jvm, Java or exe. The modes are:
| |
—StartImage | Executable that will be run. Only applies to exe mode. | |
—StartPath | Working path for the start image executable. | |
—StartClass | Main | Class that contains the startup method. Applies to the jvm and Java modes. (Not used in exe mode.) |
—StartMethod | main | Method name if differs then main |
++StartParams | List of parameters that will be passed to either StartImage or StartClass. Parameters are separated using either # or ; character. | |
—StopMode | One of jvm, Java or exe. See —StartMode for further details. | |
—StopImage | Executable that will be run on Stop service signal. Only applies to exe mode. | |
—StopPath | Working path for the stop image executable. Does not apply to jvm mode. | |
—StopClass | Main | Class that will be used on Stop service signal. Applies to the jvm and Java modes. |
—StopMethod | main | Method name if differs then main |
++StopParams | List of parameters that will be passed to either StopImage or StopClass. Parameters are separated using either # or ; character. | |
—StopTimeout | No Timeout | Defines the timeout in seconds that procrun waits for service to exit gracefully. |
—LogPath | %SystemRoot%\System32\LogFiles\Apache | Defines the path for logging. Creates the directory if necessary. |
—LogPrefix | commons-daemon | Defines the service log filename prefix. The log file is created in the LogPath directory with .YEAR-MONTH-DAY.log suffix |
—LogLevel | Info | Defines the logging level and can be either Error, Info, Warn or Debug. (Case insensitive). |
—StdOutput | Redirected stdout filename. If named auto then file is created inside LogPath with the name service-stdout.YEAR-MONTH-DAY.log. | |
—StdError | Redirected stderr filename. If named auto then file is created inside LogPath with the name service-stderr.YEAR-MONTH-DAY.log. | |
—PidFile | Defines the file name for storing the running process id. Actual file is created in the LogPath directory |
The safest way to manually install the service is to use the provided service.bat script. Administrator privileges are required to run this script. If necessary, you can use the /user switch to specify a user to use for the installation of the service.
NOTE: On Windows Vista or any later operating system with User Account Control (UAC) enabled you will be asked for additional privileges when ‘Tomcat6.exe’ is launched by the script.
If you want to pass additional options to service installer as PR_* environment variables, you have to either configure them globally in OS, or launch the program that sets them with elevated privileges (e.g. right-click on cmd.exe and select «Run as administrator»; on Windows 8 (or later) or Windows Server 2012 (or later), you can open an elevated command prompt for the current directory from the Explorer by clicking on the «File» menu bar). See issue 56143 for details.
There is a 2nd optional parameter that lets you specify the name of the service, as displayed in Windows services.
If using tomcat6.exe, you need to use the //IS// parameter.
To update the service parameters, you need to use the //US// parameter.
If you gave the service an optional name, you need to specify it like this:
To remove the service, you need to use the //DS// parameter.
If the service is running it will be stopped and then deleted.
If you gave the service an optional name, you need to specify it like this:
To run the service in console mode, you need to use the //TS// parameter. The service shutdown can be initiated by pressing CTRL+C or CTRL+BREAK. If you rename the tomcat6.exe to testservice.exe then you can just execute the testservice.exe and this command mode will be executed by default.
Tomcat supports installation of multiple instances. You can have a single installation of Tomcat with multiple instances running on different IP/port combinations, or multiple Tomcat versions, each running one or more instances on different IP/ports.
Each instance folder will need the following structure:
At a minimum, conf should contain a copy of the following files from CATALINA_HOME\conf\. Any files not copied and edited, will be picked up by default from CATALINA_HOME\conf, i.e. CATALINA_BASE\conf files override defaults from CATALINA_HOME\conf.
You must edit CATALINA_BASE\conf\server.xml to specify a unique IP/port for the instance to listen on. Find the line that contains and add an address attribute and/or update the port number so as to specify a unique IP/port combination.
To install an instance, first set the CATALINA_HOME environment variable to the name of the Tomcat installation directory. Then create a second environment variable CATALINA_BASE and point this to the instance folder. Then run «service install» command specifying a service name.
To modify the service settings, you can run tomcat6w //ES//instance1.
For additional instances, create additional instance folder, update the CATALINA_BASE environment variable, and run the service install again.