how to deploy a spring jar file on amazon ec2 instance so it can run even we close the terminal?
To deploy a Spring JAR file on an Amazon EC2 instance and ensure it continues running even after you close the terminal, you can follow these general steps:
- Launch an Amazon EC2 instance: Start by creating an EC2 instance on the AWS Management Console. Choose an appropriate instance type and configure the necessary security groups and key pairs.
- Connect to the EC2 instance: Once the EC2 instance is up and running, you need to connect to it using SSH. This allows you to execute commands on the instance remotely.
- Install Java: Update the package manager on the EC2 instance and install Java if it is not already installed. You can use a command like
sudo apt update && sudo apt install default-jre
on Ubuntu-based systems. - Upload the Spring JAR file: Transfer the Spring JAR file from your local machine to the EC2 instance. You can use secure copy (SCP) or a tool like FileZilla for this purpose.
- For example, if you have the JAR file in your local directory and you are using SCP, you can use the following command:
scp -i /path/to/key.pem /path/to/local/file.jar username@ec2-instance-ip:/path/on/ec2/
Run the JAR file: Connect to the EC2 instance using SSH and navigate to the directory where you uploaded the JAR file. Then, run the JAR file using the java -jar
command.
For example:
java -jar file.jar
- This will start your Spring application on the EC2 instance. You can verify its functionality by accessing the appropriate endpoint.
- Keep the application running after closing the terminal: By default, when you close the SSH session or terminal, the application running in the foreground will terminate. To keep it running, you can use tools like
nohup
orscreen
.
- Using
nohup
: Run the JAR file withnohup
and redirect the output to a log file. This will detach the process from the current session.
nohup java -jar file.jar > application.log &
- The application will continue running even if you close the terminal, and the logs will be written to the
application.log
file. - Using
screen
: Start a newscreen
session and run the JAR file inside it. This creates a persistent session that can be reattached later.
screen -S spring-app
java -jar file.jar
- Press
Ctrl+A
followed byCtrl+D
to detach from thescreen
session. The application will keep running, and you can reattach to the session later if needed.
These methods ensure that your Spring application continues running even after you close the terminal or disconnect from the EC2 instance. Choose the method that suits your preferences and requirements.
For creating a background service option refer this