Prerequisite:
- Java should already have
- Open and connect AWS ec2 instance using terminal
- Reach out root folder where the domain is pointing out for me it’s /var/www/HTML/
- Take pull the latest Spring Boot code from git https://bitbucket.org/***
- MVN clean install – this will convert java code with all its dependencies in a jar file
(SUDO) java -jar target/YOUR_FILE_NAME.jar (target is a folder on root)
Problem: We found a challenge while running java -jar *.jar on AWS ec2 instance in the background
Solution: Create a system service to run the Jar file in the background Linux
Ubuntu/Linux has an in-built mechanism to create custom services and enable them to start on system boot time and start/stop them as a service.
Create a bash script to run jar file Linux:
Replace the customservicename with your own service name
- Create a vi or nano file under /usr/local/bin/ by running the following commandeg: sudo vi /usr/local/bin/customservicename.shThis will open a file with the name customservicename.sh.
- Paste the following Code in opened sh.
In the below code replace the customservicename with your own service name,
JAR_FILE_PATH(Absolute Path to your jar File), and choose a PID_NAME_PATH(just replace CUSTOM_SERVICE_NAME to your customservicename keeping -PID at the end ) for the file you are going to use to store your service ID.
The only changes needed are to the first 3 variables.
- Write and quit the above file by pressing the ESC button then:wq! and give execution permissions :eg: sudo chmod +x /usr/local/bin/customservicename.sh
Read Also:- Setting Up Jenkins on Amazon EC2 Ubuntu Instance
Use The Following Commands to Test Whether Java Application Is Working:
If all the above commands do not give an error then we move forward to create a service
- Create a file under /etc/system/system/ with nano or vi and paste the example script below.
Eg. sudo vi /etc/systemd/system/customservicename.service
- Insert the following code in customservicename:
- Write and quit this file by pressing the ESC button then:wq!
Now Service is all set up.
You can enable/start/stop your Java Application as a Service using the following commands:
This should get Java Application up and running in the background as a System Service.
Original Source:- https://www.devstringx.com/run-jar-file-in-background-on-aws-ec2
No comments:
Post a Comment