Linux java service start

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.

Источник

Run a Java Application as a Service on Linux

A simple service in Linux is a program that runs in the background and performs a specific function or set of functions. These programs can be started automatically at boot time, and can be controlled using the command line or through a system service manager such as systemd or Upstart.

To create a simple service in Linux, you would first write the program that performs the desired function. This program should be designed to run in the background and to continue running even after the terminal window or SSH session is closed.

Next, you would create a script that can start, stop, and check the status of the program. This script is usually placed in the /etc/init.d/ directory and should be made executable. It would then be registered with the system service manager using command like systemctl or service .

Читайте также:  Туннель через ssh linux

Once registered, you would be able to control the service using standard command such as systemctl start|stop|status myservice or service myservice start|stop|status

Service file

A service file, also known as a unit file, is a configuration file used by the system service manager (such as systemd or Upstart) to control a service in Linux. It describes how the service should be started, stopped, and managed, and contains various settings and options that can be used to customize the behavior of the service.

A service file typically has a simple structure and is written in a declarative language. It consists of a series of sections, each of which contains specific configuration options. The most important sections are [Unit], [Service], and [Install].

  • [Unit] − contains information about the service, such as its name, description, and dependencies.
  • [Service] − contains information about how the service should be executed, such as the command to start and stop the service, and the user and group under which the service should run.
  • [Install] − contains information about how the service should be installed and activated, such as the runlevels at which the service should be started and stopped.

Here is an example of a simple service file for a service named «myservice» −

[Unit] Description=My Service After=network.target [Service] User=myservice Group=myservice ExecStart=/usr/bin/myservice Restart=always [Install] WantedBy=multi-user.target

Once the service file has been created, it should be placed in the appropriate directory (usually /etc/systemd/system or /etc/init) and then the service can be controlled using standard command such as systemctl start|stop|status myservice.

Forking Service

A forking service is a type of service that starts multiple instances of a program, each of which runs in its own process. In the context of a Java application, a forking service would involve starting multiple Java Virtual Machines (JVMs) to run the same application, with each JVM running in its own process.

Here’s one example of how you could create a forking service for a Java application −

Write a script that starts the Java application and forks a new process for each instance. This script should take command-line arguments to specify the number of instances to fork, as well as any other necessary configuration options.

Use the nohup command to run the script in the background and prevent it from being terminated when the terminal is closed.

Use a for loop to start n number of instance specified in the command line arguments

Create a service file and register it with the system service manager using systemctl or service command

[Unit] Description=My Java Forking Service [Service] ExecStart=/usr/local/bin/start-my-service.sh Restart=always User=myuser [Install] WantedBy=multi-user.target

Once registered, you would be able to control the service using standard command such as systemctl start|stop|status myservice.

Note that this is just one example of how you could create a forking service for a Java application, and there are other ways to achieve the same result depending on the specifics of the application and the environment it is running in.

Registering and Running the Service

Once you have created a service file for your Java application, you can register it with the system service manager to make it automatically start at boot time and allow you to control it using standard commands.

Читайте также:  Отредактировать файл linux ubuntu

The process of registering and running the service will depend on which system service manager you are using.

For example, with systemd, you can use the following commands to register and run the service −

Copy the service file to the /etc/systemd/system directory.

Reload systemd to read the service file

Enable the service to start automatically at boot time

systemctl enable myservice
systemctl start myservice

Check the status of the service

systemctl status myservice

With sysvinit based distro like Ubuntu 14.04 and earlier uses update-rc.d

update-rc.d myservice defaults

With Upstart, the process is similar, but you will use the initctl command instead of systemctl .

It’s worth noting that if you’re running your application in a container like docker, you don’t have to worry about this process of registering and running the service. you should handle the container to start at boot.

Run a Java Application as a Service on Linux

Running a Java application as a service on Linux involves creating a service file that describes how the application should be started, stopped, and managed, and then registering that service file with the system service manager.

Here is an example of how you could run a Java application as a service on Linux −

Create a script that starts your Java application. This script should use the nohup command to run the application in the background and prevent it from being terminated when the terminal is closed.

nohup java -jar /path/to/your/application.jar &

Create a service file with the desired configuration for your service. The service file should contain information such as the name of the service, the user and group to run the service as, and the command to start and stop the service.

[Unit] Description=My Java Application Service After=network.target [Service] User=myuser Group=myuser ExecStart=/usr/local/bin/start-my-application.sh Restart=always [Install] WantedBy=multi-user.target

Register the service file with the system service manager. On systems using systemd, you can use the systemctl command to register the service, such as

systemctl enable myservice
systemctl start myservice

Check the status of the service

systemctl status myservice

It is worth noting that the above steps and examples are for a system that uses systemd as service manager. The process for other service managers (like SysV or Upstart) is slightly different, but the general idea is the same.

Conclusion

Running a Java application as a service on Linux involves creating a service file that describes how the application should be started, stopped, and managed, and then registering that service file with the system service manager.

The process involves creating a script that starts your Java application using the nohup command to run the application in the background and prevent it from being terminated when the terminal is closed.

Источник

How do I run Java as a service on Ubuntu?

So after 2 days (yes I’m a complete rookie when it comes to servers) trying to get this working I give up and turn to SO for help 🙂 I want to start my java app on start, log to a logfile. That’s it 🙂

start on runlevel [2345] stop on runlevel [!2345] #Respawn the process if it crashes #If it respawns more than 10 times in 5 seconds stop respawn respawn limit 10 5 expect fork script cd /home/ubuntu/admin/ mvn spring-boot:run > /var/log/upstart/admin.log 2>&1 end script 

Running «sudo start admin» works and I get «admin start/running» in console.. No log is created and the java app is not started.. ? What am I missing? How do I run Java as a service on Ubuntu?

Читайте также:  Astra linux сервер домена

This Q is not about programming as defined for StackOverflow. It may be more appropriate on the related sites askubuntu.com OR ServerFault.com. Consider using the flag link at the bottom of your Q and ask the moderator to move it there. Good luck.

@shellter how is it not programming? Service configuration is part of the product source in many cases. I debated the same thing myself and realized it’s completely valid as a question here.

@AlainO’Dea : I agree, there’s no easy line. While I used to advocate strictly for if/else sort of coding issues, I realize that is too narrow AND there really isn’t a StackExchange site to handle many issues that crop up. But when I see a lot of linux/ubuntu specific key words in a Q, my vote is to send questioner to sites as I have mentioned above. My vote to close is strictly MHO, so I leave it to the votes AND good answers to decide if the Q should really be closed or not. Good answer, by the way :-). Good luck to all.

1 Answer 1

I don’t mean to sidetrack, but I’ve deployed Java applications on Ubuntu in production since 2010 and had very little success with Upstart. I use init.d scripts and start-stop-daemon. Side bonus: it works on more distros.

Create /etc/init.d/my-java-app:

#!/bin/sh # # my-java-app My Java App # # chkconfig: - 80 05 # description: Enable My Java Application # ### BEGIN INIT INFO # Provides: my-java-app # Required-Start: $remote_fs $network # Required-Stop: $remote_fs $network # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Description: My Java Application # Short-Description: Enable My Java Application ### END INIT INFO DESC="my java app" NAME=my-java-app PIDFILE=/var/run/$NAME.pid RUN_AS=ubuntu WORK_DIR=/home/ubuntu/admin DAEMON=/usr/bin/mvn DAEMON_OPTS="spring-boot:run" # Read configuration variable file if it is present [ -r /etc/default/$NAME ] && . /etc/default/$NAME # Load the VERBOSE setting and other rcS variables . /lib/init/vars.sh # Define LSB log_* functions. # Depend on lsb-base (>= 3.2-14) to ensure that this file is present # and status_of_proc is working. . /lib/lsb/init-functions do_start() < start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE \ --background \ --chuid $RUN_AS \ --chdir $WORK_DIR \ --exec $DAEMON -- $DAEMON_OPTS >do_stop() < start-stop-daemon --stop --quiet --pidfile $PIDFILE if [ -e $PIDFILE ] then rm $PIDFILE fi >case "$1" in start) echo -n "Starting $DESC: $NAME" do_start echo "." ;; stop) echo -n "Stopping $DESC: $NAME" do_stop echo "." ;; restart) echo -n "Restarting $DESC: $NAME" do_stop sleep 1 do_start echo "." ;; status) status_of_proc -p $PIDFILE "$DAEMON" "$NAME" && exit 0 || exit $? ;; *) echo "usage: $NAME " exit 1 ;; esac 

Make it belong to root, make it executable, and set it up to run on startup with:

sudo chown root:root /etc/init.d/my-java-app sudo chmod 755 /etc/init.d/my-java-app sudo update-rc.d my-java-app defaults 

To start the service you can run:

sudo service my-java-app start 

To stop the service you can run:

sudo service my-java-app stop 

This is based on a simplified version of the /etc/init.d/skeleton file included by Ubuntu.

The man page for start-stop-daemon is worth looking at if you want to tweak this further.b

Источник

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