Start java application as service

Java application as Windows Service

In this blog post, I show you how to install a Java application with WinSW as a Windows service. WinSW is an executable binary, which can be used to wrap and manage any custom process as a Windows service.

Demo

First, we need a demo application. I use a simple Quarkus application for this purpose. You can install any Java application as a service. Usually, you install applications that run forever like an HTTP server in this case.

To bootstrap a Quarkus application run this command

mvn io.quarkus:quarkus-maven-plugin:2.5.1.Final:create -DprojectGroupId=com.testlab -DprojectArtifactId=testservice -DclassName="com.testlab.testservice.GreetingResource" -Dpath="/hello" cd testservice 

We use the application as is with just a small change. I want to create a fat jar. A jar with all dependent libraries included.
You can package your application in any way you want. In this case, I prefer the fat jar installation because I only have to copy one file.

Open src\main\resources\application.properties and insert the following property

quarkus.package.type=uber-jar 

Now you can package the application with .\mvnw.cmd package . You find the jar in the target folder: testservice-1.0.0-SNAPSHOT-runner.jar

Preparation

You can proceed in different ways. I usually create a new folder where I copy all the files into it that are needed to run the application as a service. Copy the jar from the target folder into this directory.

Читайте также:  Java class source codes

Java

Next, I download the Java Runtime and also copy it into this folder. This is optional. Your service can access a globally installed Java. But I like to have everything contained in one folder and don’t have to worry about somebody updating or removing the globally installed Java.

I usually download Java from Adoptium. On the release page, you find the ZIP file with the JDK for Windows.

Download the ZIP file and unzip it into the install folder. I unzip it into the java subfolder, so the java.exe is accessible with this path java\bin\java.exe

WinSW

Open the release page of the WinSW project and download the executable suitable for your platform.
https://github.com/winsw/winsw/releases

For this demo installation, I download WinSW.NET461.exe . WinSW runs on Windows with .NET Framework 2.0, 4.0 or 4.6.1. If you need to install the service on a Windows without .NET framework, download the core variant WinSW-x64.exe for 64-bit or WinSW-x86.exe` for 32-bit systems.

Copy the executable also into the folder where your jar resided. Rename the WinSW executable to any name you like. For this example, I rename it to testservice.exe . Create an XML with the same base name: testservice.xml . Make sure that the exe and XML file are located in the same folder.

Open the XML file and paste the following code into it.

service> id>testserviceid> name>Test Servicename> description>This is a test service.description> executable>"%BASE%\java\bin\java"executable> arguments>-jar "%BASE%\testservice-1.0.0-SNAPSHOT-runner.jar"arguments> logmode>rotatelogmode> stopparentprocessfirst>truestopparentprocessfirst> service> 

Check the executables path and arguments. %BASE% is an environment variable that points to the directory where the WinSW executable is located. If you want to start the application with a Java that is on the %PATH% , just use java .

Relevant here is . This tells WinSW to shutdown the parent process first. In our case this is useful because the main process opens a console ( java ), which can respond to Ctrl+C and will gracefully shutdown the child process (the Java application).

Check out this wiki page to learn more about all the supported options:
https://github.com/winsw/winsw/blob/master/doc/xmlConfigFile.md

Directory structure

The directory structure of my install folder.

testservice.exe testservice.xml testservice-1.0.0-SNAPSHOT-runner.jar java bin java.exe . conf legal lib . 

Installation

With everything in place you install the Windows service with this command

The WinSW command supports the following options:

  • install : Install the service
  • uninstall : Uninstall the service
  • start : Start the installed service
  • stop : Stop the service
  • restart : Restart the service
  • status : Show the current service status (NonExistent, Started, Stopped)

The service by default is installed with start mode Automatic . That means Windows starts the service when it boots up. You can change that with the configuration in the XML file.

To test the installation, open http://localhost:8080 in a browser. You should see the default start page of Quarkus. To test if the graceful shutdown works, stop the service

Open the file testservice.out.log .

2020-05-06 05:30:52,501 INFO [io.quarkus] (main) Profile prod activated. 2020-05-06 05:30:52,501 INFO [io.quarkus] (main) Installed features: [cdi, resteasy] 2020-05-06 05:30:54,801 INFO [io.quarkus] (main) testservice stopped in 0.032s 

We see that the application shutdown gracefully because of the testservice stopped log entry.

Note that WinSW creates by default three logs files:

  • .out.log : Console output from the application ( System.out.println )
  • .err.log : Error output from the application ( System.err.println )
  • .wrapper.log : Log output from WinSW itself

That concludes this tutorial about installing any Java applications as Windows Service. Optionally you could try and create a native image of your application with GraalVM. The service installation does not change a lot. You don’t need the JRE anymore and have to change accordingly.

Источник

Running a Java Application as a Service

To control our application, we’re going to run it as a systemd service. Wikipedia defines systemd as:

a software suite that provides an array of system components for Linux operating systems. Its main aim is to unify service configuration and behavior across Linux distributions; systemd’s primary component is a «system and service manager» — an init system used to bootstrap user space and manage user processes.

To create a service, we need to have the relevant access to the server, so we need to ensure we have sudo access.

The first stage in defining the application as a service, is to create a file within the /etc/systemd/system directory with a name of myapp.service

/etc/systemd/system/myapp.service 

Within this file, we need to add 3 sections. [Unit] defines the description of the service, [Service] defines how the service is executed and [Install] tells the operating system when to run the application. For example

[Unit] Description=My Application As A Service [Service] User=myapp_user Group=myapp_group Type=simple ExecStart= java -jar /home/ubuntu/myapp/myapp.jar -Xmx512m –Xms512m -XX:MaxNewSize=384m -XX:MaxPermSize=128m SuccessExitStatus=143 [Install] WantedBy=multi-user.target 

Let’s take a look at each of these sections in turn.

[Unit]

This section simply contains one entry which is the description of the service. Note, the name of the service is defined by the name of the file within the /etc/systemd/system directory.

[Service]

This section defines details that the operating system requires to be able to start the service. Firstly, the User and Group specify the security details for the application to run. The application is run as this specified user and group and has their permissions.

Type can be set to simple for most cases. This defines that the application will run immediately without forking any other processes. For a definition of the other options available here, check out the man pages for systemd.

Next, ExecStart specifies the command that is used to run the application. Here, we specify the entire command line (including java and any parameters) to run the application. This can be very useful as we can specify which version of Java to use here, so an application can be configured to run with any required JVM, and not only with the system’s default JVM. Any JVM properties or application variables can be configured here.

Finally, as we’re running a Java application, we need to tell it how to play properly with systemd. When a Java application is killed via a SIGTERM event, the JVM will close down cleanly but will return an exit code of 143. Adding this as a SuccessExitStatus tells systemd that the application has closed cleanly in this situation.

[Install]

The last section basically tells systemd that if the application is configured to start at server boot time, then do so as part of the normal boot process. This tells systemd that the application can start at boot time, but not that it necessarily will. Read on for how we do that.

Controlling the Service

Once the .service file has been created, we need to tell systemd that we have a new service. This is achieved by executing:

sudo systemctl daemon-reload 

Once executed, we can start and stop the service via:

sudo systemctl start myapp sudo systemctl stop myapp 

We can get the status of the application by executing:

sudo systemctl status myapp 

Finally, if we want to tell the systemd to start the application at boot time, we can execute the following command:

sudo systemctl enable myapp 

Restarting upon Failure

Now that we’ve seen how to create and manage a service, the only thing remaining is to tell systemd to restart the service in case of a failure.

That can be achieved by adding the following entries into the [Service] section of the file.

Restart=on-failure RestartSec=10s 

This configuration tells systemd to restart the service 10s after a failure (you can obviously customise this to your required time interval).

There are other options available here, for example, when the service is to restart and how many attempts to be made. For more information, check out the man pages for systemd.

Conclusion

In this post we’ve seen how to run a Java application as a service using systemd, and how to control it. We’ve seen how to start the service at boot time and how to restart the service upon failure.

Источник

Run Your Java App as a Service on Ubuntu

Join the DZone community and get the full member experience.

Say you have a JAR file and you need to run it as a service. Additionally, you want it to start automatically if/when system restarts.

Ubuntu has a built-in mechanism to create custom services, enabling them to get started at system boot time and start/stop them as a service. In this post, I am going to share a simple and elegant way to create a service wrapper for your JAR file so you can run it as a service. Here we go.

Step 1: Create a Service

sudo vim /etc/systemd/system/my-webapp.service

Copy/paste the following into the file /etc/systemd/system/my-webapp.service :

[Unit] Description=My Webapp Java REST Service [Service] User=ubuntu # The configuration file application.properties should be here: #change this to your workspace WorkingDirectory=/home/ubuntu/workspace #path to executable. #executable is a bash script which calls jar file ExecStart=/home/ubuntu/workspace/my-webapp SuccessExitStatus=143 TimeoutStopSec=10 Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target

Step 2: Create a Bash Script to Call Your Service

Here’s the bash script that calls your JAR file: my-webapp

#!/bin/sh sudo /usr/bin/java -jar my-webapp-1.0-SNAPSHOT.jar server config.yml

Don’t forget to give your script execute permission: sudo chmod u+x my-webapp

Step 3: Start the Service

sudo systemctl daemon-reload sudo systemctl enable my-webapp.service sudo systemctl start my-webapp sudo systemctl status my-webapp

Step 4: Set Up Logging

First, run: sudo journalctl —unit=my-webapp . See real-time logs by using the -f option.

If you want to trim them, use -n to view the specified number of lines of the log:

sudo journalctl -f -n 1000 -u my-webapp

Tail the live log using the -f option:

sudo journalctl -f -u my-webapp

Stop the service by using:

sudo systemctl stop my-webapp

That’s it! Enjoy and show your support if you like it. Thanks!

Published at DZone with permission of Muhammad Sarwar . See the original article here.

Opinions expressed by DZone contributors are their own.

Improving Storage Security and Compliance: Best Practices for Implementing Granular Authentication in Storage

Источник

Оцените статью