DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Boot: Handle AWS RDS Password Change or Rotation Without Restarting
  • How to Build a Chat App With Spring Boot and DynamoDB
  • Spring2quarkus — Spring Boot to Quarkus Migration
  • A Practical Guide to Creating a Spring Modulith Project

Trending

  • Modern Test Automation With AI (LLM) and Playwright MCP
  • Efficient API Communication With Spring WebClient
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Go 1.24+ Native FIPS Support for Easier Compliance
  1. DZone
  2. Coding
  3. Frameworks
  4. Integrate Spring Boot and EC2 Using Cloudformation

Integrate Spring Boot and EC2 Using Cloudformation

Getting your Spring application up and running on top of an EC2 instance is pretty simple.

By 
Emmanouil Gkatziouras user avatar
Emmanouil Gkatziouras
DZone Core CORE ·
Dec. 28, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
10.3K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous blog, we integrated a Spring Boot application with Elastic beanstalk. The application was a servlet-based application responding to requests.

In this tutorial, we are going to deploy a Spring Boot application that executes some scheduled tasks on an EC2 instance.

The application will be pretty much the same application taken from the official Spring guide with some minor differences in packages.

The name of our application will be ec2-deployment:

 rootProject.name = 'ec2-deployment' 

We will schedule a task to our Spring Boot application.

package com.gkatzioura.deployment.task; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.scheduling.annotation.Scheduled; 
import org.springframework.stereotype.Component; 
/** * Created by gkatzioura on 12/16/16. */ 
@Component public class SimpleTask 
{ 
  private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTask.class);
 @Scheduled(fixedRate = 5000) 

 public void reportCurrentTime() 
 { 
   LOGGER.info("This is a simple task on ec2"); 
 } 
} 

The next step is to build the application and deploy it to our s3 bucket.

 gradle build aws s3 cp build/libs/ec2-deployment-1.0-SNAPSHOT.jar s3://{your bucket name}/ec2-deployment-1.0-SNAPSHOT.jar 

What comes next is a bootstrapping script in order to run our application once the server is up and running.

 #!/usr/bin/env bash aws s3 cp s3://{bucket with code}/ec2-deployment-1.0-SNAPSHOT.jar /home/ec2-user/ec2-deployment-1.0-SNAPSHOT.jar sudo yum -y install java-1.8.0 sudo yum -y remove java-1.7.0-openjdk cd /home/ec2-user/ sudo nohup java -jar ec2-deployment-1.0-SNAPSHOT.jar > ec2dep.log 

This script is pretty much self-explanatory. We download the application from the bucket we uploaded it from previously, we install the Java version needed, and then we run the application (this script serves us for example purposes; there are certainly many ways to set up your Java application running on Linux).

The next step would be to proceed to our Cloudformation script. Since we will download our application from s3, it is essential to have an IAM policy that will allow us to download items from the s3 bucket we used previously. Therefore, we will create a role with the policy needed.

 "RootRole": { "Type": "AWS::IAM::Role", 
              "Properties": { "AssumeRolePolicyDocument": 
                             { "Version" : "2012-10-17", 
                              "Statement": [ 
                                { "Effect": "Allow", "Principal": 
                                 { "Service": [ "ec2.amazonaws.com" ] }, 
                                 "Action": [ "sts:AssumeRole" ] } ] }, 
                             "Path": "/", 
                             "Policies": [
                               { "PolicyName": "root", 
                                "PolicyDocument": 
                                { "Version" : "2012-10-17", "Statement": 
                                 [ { "Effect": "Allow", "Action": 
                                    [ "s3:Get*", "s3:List*" ],
                                    "Resource": {"Fn::Join" : [ "",
                                                               [ "arn:aws:s3:::",
{"Ref":"SourceCodeBucket"},"/*"] ] } } ] } } ] } } 

The next step is to encode our bootstrapping script to Base64 in order to be able to pass it as user data. Once the EC2 instance is up and running, it will run the Shell commands previously specified.

The last step is to create our instance profile and specify the EC2 instance to be launched.

 "RootInstanceProfile": 
{ "Type": "AWS::IAM::InstanceProfile", 
 "Properties": 
 { "Path": "/", "Roles": [ { "Ref": "RootRole" } ] } }, 
"Ec2Instance":{ "Type":"AWS::EC2::Instance", 
             "Properties":{ "ImageId":"ami-9398d3e0", 
                           "InstanceType":"t2.nano", 
                           "KeyName":"TestKey", 
                           "IamInstanceProfile": 
                           {"Ref":"RootInstanceProfile"}, 
"UserData":"IyEvdXNyL2Jpbi9lbnYgYmFzaA0KYXdzIHMzIGNwIHMzOi8ve2J1Y2tldCB3aXRoIGNvZGV9L2VjMi1kZXBsb3ltZW50LTEuMC1TTkFQU0hPVC5qYXIgL2hvbWUvZWMyLXVzZXIvZWMyLWRlcGxveW1lbnQtMS4wLVNOQVBTSE9ULmphcg0Kc3VkbyB5dW0gLXkgaW5zdGFsbCBqYXZhLTEuOC4wDQpzdWRvIHl1bSAteSByZW1vdmUgamF2YS0xLjcuMC1vcGVuamRrDQpjZCAvaG9tZS9lYzItdXNlci8NCnN1ZG8gbm9odXAgamF2YSAtamFyIGVjMi1kZXBsb3ltZW50LTEuMC1TTkFQU0hPVC5qYXIgPiBlYzJkZXAubG9n" 
                          } } 

KeyName stands for the SSH key name, in case you want to log into the ec2 instance.

So, we are good to go and create our Cloudformation stack. You have to add the CAPABILITY_IAM flag.

 aws s3 cp ec2spring.template s3://{bucket with templates}/ec2spring.template aws cloudformation create-stack --stack-name SpringEc2 --parameters ParameterKey=SourceCodeBucket,ParameterValue={bucket with code} --template-url https://s3.amazonaws.com/{bucket with templates}/ec2spring.template --capabilities CAPABILITY_IAM 

That’s it. Now you have your spring application up and running on top of an EC2 instance.

You can download the source code from GitHub.

Spring Framework AWS Spring Boot application

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot: Handle AWS RDS Password Change or Rotation Without Restarting
  • How to Build a Chat App With Spring Boot and DynamoDB
  • Spring2quarkus — Spring Boot to Quarkus Migration
  • A Practical Guide to Creating a Spring Modulith Project

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!