Skip to main content

AWS Spring - Deploy Spring Boot application to AWS EC2

Greetings!

AWS and Spring are two of the most needed skills Java developer needs these days. It is no fun to just learn theory. Let's host our tiny Spring backed application in AWS.

Assumption: You are comfortable with Spring, AWS but exploring how to deploy.

In this basic setup, we are going to use the easiest way in contrast to learning. We had a running system in this way which had around 8~10 microservices. I missed those days anyway.

It is very primitive but it works!

Steps

Let's define what we are going to do.
  • Create an EC2 instance
  • Create Spring Boot app
  • Setup EC2
  • Copy Spring boot application into EC2 and run

Create an EC2 instance

I assume you already know this step. However, there are a few things to note.
Make sure to download your keypair (mykeypair.pem) and set the correct permission (chmod +400)
Security group - Add 2 rules to allow ssh (port 22) and HTTP access with port 8080

Create a Spring boot application

Go to https://start.spring.io/ and generate your project. Add a simple endpoint so that we can access it via browser.

Setup EC2

We are going to deploy a Spring boot application that bundles with a server (default to Tomcat). Hence we do not need to set up a server. However, we need to install Java.
Follow these steps which are self-explanatory.
$ sudo ssh -i MyKeyPair.pem ec2-user@<ip>
$ java -version
$ sudo -i
$ yum install java-11
$ alternatives --config java
$ java -version

Copy Sprint boot application into EC2

Create the jar of your application. I assume you know how to do that. Then we need to copy our jar into EC2 from our local computer.
$ sudo scp -i MyKeyPair.pem myapp.jar ec2-user@<ip>:/home/ec2-user

Run the application

Simply run it using the Java command. Note that when you exit from the shell, the app will be terminated with this. If you want to keep it in the background using "nohup".
$ java -jar myapp.jar
or
$ nohup java -jar app.jar > output.log &
Now we can access our application using the EC2 public IP. <public_id>:8080
Make sure to allow access to your port via security group.

What have we achieved?

We have successfully deployed a Spring Boot application into AWS. Even though it looks very basic it has a less learning curve as well as less money to spend. However, this has a lot of manual work which is not the idea of the cloud. But anyway, this is a good starting point.

Happy learning :)