Run your Java Application as a Service in an EC2 Instance (Amazon Linux)
Before creating a service, first you need to connect to your ec2 instance. It’s either via windows using putty or mac /linux using an ssh client. You can refer to the link of the aws documentation below:
Assuming you’ve already connected to your ec2 instance. Let’s go create a service for your java application! :)
Create a service
In your /home/ec2-user directory
sudo vim /etc/systemd/system/your-application.service
Insert the code below into your-application.service:
[Unit]
Description=Java Application as a Service[Service]
User=ec2-user#change this directory into your workspace
#mkdir workspace
WorkingDirectory=/home/ec2-user/workspace#path to the executable bash script which executes the jar file
ExecStart=/bin/bash /home/ec2-user/workspace/your-script.shSuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5[Install]
WantedBy=multi-user.target
Create a bash script to call your service
/home/ec2-user/workspace directory
sudo nano your-script.sh
The below script includes a java command to execute the .jar file which also calls the application and system properties
#!/bin/shjava -Dexternal.sys.properties=file:system.properties
-Dexternal.app.properties=file:application.properties -jar your-application.jar
Update the script permission to be executable:
Go to your bash script directory:
/home/ec2-user/workspace/ directory
sudo chmod u+x your-script.sh
or
sudo chmod 744 your-script.sh
Start the service
sudo systemctl daemon-reload
sudo systemctl enable your-application.service
sudo systemctl start your-application
sudo systemctl status your-application -l
Stop the service
sudo systemctl stop your-application
So that’s it. Hope it could help you! :)