Summary

You already have a Java project and have an executable JAR/WAR file. Now, you want to develop an application that uses the Web Services bundled in your JAR/WAR file. In an effort to keep your development environment tidy it makes sense to run your Java project on another machine, but where? You have a Raspberry Pi 4! Of course! Let’s run the JAR as a service on the Raspberry Pi and access our services through the local network!

For ease of use, we also want to configure our JAR file to start and stop with the RPi4. Follow along with this guide to learn how you can create a systemd service that will keep your JAR available during development.

What you need

Creating the Service File

In order to run your JAR, you will need to create a .service file that executes your JAR/WAR file. Before creating the service, make sure that you have already copied your JAR to the RPi. In the guide, we’ve put our JAR in /home/pi/Documents/spring/.

[Unit]
Description=Java Service
After=network.target

[Service]
ExecStart=java -jar /home/pi/Documents/spring/<jar_name_here>.jar
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

In this service file we are telling the service that it should only start after “network.target” has been started, this is essential if your JAR exposes Web Services.

ExecStart is where we define the command that we want to execute when the service starts. You can either put the command directly into this attribute OR you can place your command into a script and call the script.

Note: If you choose to place the command directly into your service file, you must use an absolute path when referencing files.

Finally, save this file with the .service suffix. e.g. java_start.service

Register the Service

sudo cp <your_service_file>.service /etc/systemd/system/<your_service_file>.service
copy service file to system directory
Copy service file from Desktop to System

Running this command will copy your service file into the system services directory of the Raspberry Pi. Time to test it out.

sudo systemctl start <my_service_file>.service
...
sudo systemctl stop <my_service_file>.service
start service from terminal
Run service to test it out

Once copied, try to start the service and interact with your JAR. If this was successful, then, configure your service to start automatically.

sudo systemctl enable <my_service_file>.service
...
sudo systemctl disable <my_service_file>.service

Test the Service!

This is the moment of truth! Reboot your Raspberry Pi. Wait until it finishes starting. Then, try to access your application!

If your JAR/WAR exposes some HTTP endpoints, try accessing those endpoints via Postman to validate they are available.

That’s it! Now your JAR files will start and stop with your Raspberry Pi 4. Happy coding!