Type something to search...
How to Deploy a Spring Boot Application to AWS CloudFormation

How to Deploy a Spring Boot Application to AWS CloudFormation

Introduction

Deploying a Spring Boot application to the cloud can provide many benefits such as scalability and easy management. AWS CloudFormation is a service that allows for the creation and management of infrastructure as code, making it easy to provision and update resources. In this article, we will go over the steps to deploy a Spring Boot application to AWS CloudFormation. We will cover how to create a CloudFormation template, package the application into a deployable artifact, update the stack with the new version of the application, and set up continuous deployment to automatically update the application when new code is pushed to a version control repository. By the end of this guide, you will have a solid understanding of how to deploy a Spring Boot application to AWS CloudFormation.

Prerequisites

A few requirements must be satisfied before beginning to deploy a Spring Boot application to AWS CloudFormation.

  • An AWS account is required to use AWS CloudFormation.
  • The Spring Boot application should be already built and ready for deployment.
  • Familiarity with AWS CloudFormation and the AWS Management Console is recommended.
  • AWS CLI and AWS SDK should be installed in the local machine.
  • AWS IAM user with permissions to create and update CloudFormation stacks.
  • Familiarity with the Spring Boot application’s dependencies and configuration.

Before starting the deployment process, make sure you have met all the requirements.

Creating a CloudFormation template

What is a CloudFormation template?

AWS CloudFormation is a tool that enables you to model and provide all the resources required for your applications across all of your AWS accounts and locations in an automated and secure way using a single YAML or JSON file. Known as a CloudFormation template, this file.

All the AWS resources you wish to generate and configure for your application, together with their interdependencies, are listed in a CloudFormation template. The template is a text file with JSON or YAML formatting. You may use this straightforward, reusable, and simple-to-read framework to represent your infrastructure. To create, edit, and delete stacks using CloudFormation templates, utilize the AWS Management Console, AWS Command Line Interface (CLI), or SDKs.

A potent tool that enables you to design your infrastructure as code is the CloudFormation template. This implies that you may test your templates in various settings, version control them, and undo changes as needed. You may automate the construction and administration of your resources with CloudFormation, which can save you time and lower the possibility of human mistake.

Creating the template

You may create a CloudFormation template in one of three ways:

  • From Scratch
  • Using one of the sample templates provided by AWS CloudFormation
  • Using the AWS CloudFormation Designer

From Scratch

You can create a template by hand using a text editor. You can use either JSON or YAML to write the template, however, YAML is more human-readable and less verbose.

Using one of the sample templates provided by AWS CloudFormation

AWS CloudFormation provides a number of sample templates that cover different scenarios and use cases. You can use these templates as a starting point and customize them to suit your needs.

Using the AWS CloudFormation Designer

The AWS CloudFormation Designer is a visual editor that allows you to create a CloudFormation template by dragging and dropping resources. You can use the AWS CloudFormation Designer to create a template for a simple application, but it is not recommended for more complex applications.

Template structure

Six primary parts make up a CloudFormation template:

  1. “AWSTemplateFormatVersion”: This field is required and specifies the format version of the CloudFormation template. The current version is “2010-09-09”
  2. “Description”: This field is optional and provides a brief description of the stack and its resources.
  3. “Metadata”: This field is optional and provides additional information about the template and its resources.
  4. “Parameters”: This field is optional and allows you to pass input values to the template at runtime. This allows you to customize the stack’s resources.
  5. “Resources”: This field is required and defines the stack’s resources and their properties.
  6. “Outputs”: This field is optional and allows you to output values from the stack’s resources. This can be useful for displaying information about the stack’s resources after it is created.

Understanding a CloudFormation template’s structure and the many elements it consists of is crucial since doing so will make it easier for you to develop and alter your templates.

Creating a CloudFormation template for a Spring Boot application

We’ll build a CloudFormation template for a Spring Boot application in this part. Although we will start from scratch, you are free to apply any of the techniques mentioned in the previous section. The template will deploy the Spring Boot application, set up Java, and establish an EC2 instance. To increase the application’s scalability and fault tolerance, you may utilize advanced AWS services like a load balancer, auto-scaling groups, and others.

Template structure

The template will consist of the following sections:

  • AWSTemplateFormatVersion
  • Description
  • Parameters
  • Metadata
  • Resources
  • Outputs

AWSTemplateFormatVersion

The first section of the template is the AWSTemplateFormatVersion section. This section is required and specifies the format version of the CloudFormation template. The current version is “2010-09-09”.

spring-boot-cloudformation-template-cfn.yaml
1
AWSTemplateFormatVersion: 2010-09-09

Description

The next section is the Description section. This section is optional and provides a brief description of the stack and its resources.

spring-boot-cloudformation-template-cfn.yaml
1
Description: >-
2
This template deploys a Spring Boot application to AWS CloudFormation.

Parameters

The next section is the Parameters section. This section is optional and allows you to pass input values to the template at runtime. This allows you to customize the stack’s resources.

spring-boot-cloudformation-template-cfn.yaml
1
Parameters:
2
KeyName:
3
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
4
Type: AWS::EC2::KeyPair::KeyName
5
ConstraintDescription: must be the name of an existing EC2 KeyPair.
6
InstanceType:
7
Description: WebServer EC2 instance type
8
Type: String
9
Default: t2.micro
10
AllowedValues:
11
- t2.nano
12
- t2.micro
13
- t2.small
14
- t2.medium
15
- t2.large
16
- t2.xlarge
17
- t2.2xlarge
18
- t3.nano
19
- t3.micro
20
- t3.small
21
- t3.medium
22
- t3.large
23
- t3.xlarge
24
- t3.2xlarge
25
- m1.small
26
- m1.medium
27
- m1.large
28
- m1.xlarge
29
- m2.xlarge
30
- m2.2xlarge
31
- m2.4xlarge
32
- m3.medium
33
- m3.large
34
- m3.xlarge
35
- m3.2xlarge
36
- m4.large
37
- m4.xlarge
38
- m4.2xlarge
39
- m4.4xlarge
40
- m4.10xlarge
41
- m4.16xlarge
42
- m5.large
43
- m5.xlarge
44
- m5.2xlarge
45
- m5.4xlarge
46
- m5.12xlarge
47
- m5.24xlarge
48
- m5d.large
49
- m5d.xlarge
50
- m5d.2xlarge
51
- m5d.4xlarge
52
- m5d.12xlarge
53
- m5d.24xlarge
54
- c1.medium
55
- c1.xlarge
56
- c3.large
57
- c3.xlarge
58
- c3.2xlarge
59
- c3.4xlarge
60
- c3.8xlarge
61
- c4.large
62
- c4.xlarge
63
- c4.2xlarge
64
- c4.4xlarge
65
- c4.8xlarge
66
- c5.large
67
- c5.xlarge
68
- c5.2xlarge
69
- c5.4xlarge
70
- c5.9xlarge
71
ConstraintDescription: must be a valid EC2 instance type.
72
AMI:
73
Description: >-
74
The ID of the Amazon Machine Image (AMI) that you want to use to launch
75
the instances.
76
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
77
Default: /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2

The template contains three parameters:

  • KeyName: This parameter specifies the name of an existing EC2 KeyPair to enable SSH access to the instance.
  • InstanceType: This parameter specifies the EC2 instance type.
  • AMI: This parameter specifies the ID of the Amazon Machine Image (AMI) that you want to use to launch the instances.

Metadata

The next section is the Metadata section. This section is optional and provides additional information about the template and its resources.

spring-boot-cloudformation-template-cfn.yaml
1
Metadata:
2
AWS::CloudFormation::Interface:
3
ParameterGroups:
4
- Label:
5
default: EC2 Instance Configuration
6
Parameters:
7
- KeyName
8
- InstanceType
9
- AMI
10
ParameterLabels:
11
KeyName:
12
default: EC2 Key Pair
13
InstanceType:
14
default: EC2 Instance Type
15
AMI:
16
default: Amazon Machine Image (AMI)

Resources

The next section is the Resources section. This section is required and defines the stack’s resources and their properties.

spring-boot-cloudformation-template-cfn.yaml
1
Resources:
2
VPC:
3
Type: AWS::EC2::VPC
4
Properties:
5
CidrBlock: 15.0.0.0/16
6
EnableDnsSupport: true
7
EnableDnsHostnames: true
8
Tags:
9
- Key: Name
10
Value: !Sub ${AWS::StackName}-VPC
11
12
PublicSubnet:
13
Type: AWS::EC2::Subnet
14
DependsOn:
15
- VPC
16
Properties:
17
VpcId: !Ref VPC
18
CidrBlock: 15.0.0.0/24
19
AvailabilityZone: !Select [0, !GetAZs '']
20
MapPublicIpOnLaunch: true
21
Tags:
22
- Key: Name
23
Value: !Sub ${AWS::StackName}-PublicSubnet
24
25
IGW:
26
Type: AWS::EC2::InternetGateway
27
Properties:
28
Tags:
29
- Key: Name
30
Value: !Sub ${AWS::StackName}-IGW
31
VPCGatewayAttachment:
32
Type: AWS::EC2::VPCGatewayAttachment
33
DependsOn:
34
- VPC
35
- IGW
36
Properties:
37
VpcId: !Ref VPC
38
InternetGatewayId: !Ref IGW
39
40
PublicRouteTable:
41
Type: AWS::EC2::RouteTable
42
DependsOn:
43
- VPC
44
Properties:
45
VpcId: !Ref VPC
46
Tags:
47
- Key: Name
48
Value: !Sub ${AWS::StackName}-PublicRouteTable
49
50
PublicRoute:
51
Type: AWS::EC2::Route
52
Properties:
53
RouteTableId: !Ref PublicRouteTable
54
DestinationCidrBlock: 0.0.0.0/0
55
GatewayId: !Ref IGW
56
57
PublicSubnetRouteTableAssociation:
58
Type: AWS::EC2::SubnetRouteTableAssociation
59
DependsOn:
60
- PublicRouteTable
61
- PublicSubnet
62
Properties:
63
SubnetId: !Ref PublicSubnet
64
RouteTableId: !Ref PublicRouteTable
65
66
SpringBootSG:
67
Type: AWS::EC2::SecurityGroup
68
DependsOn:
69
- VPC
70
Properties:
71
GroupDescription: Security group for Spring Boot application
72
VpcId: !Ref VPC
73
SecurityGroupIngress:
74
- IpProtocol: tcp
75
FromPort: 22
76
ToPort: 22
77
CidrIp: 0.0.0.0/0
78
- IpProtocol: tcp
79
FromPort: 8080
80
ToPort: 8080
81
CidrIp: 0.0.0.0/0
82
Tags:
83
- Key: Name
84
Value: !Sub ${AWS::StackName}-SpringBootSG
85
86
S3CodeBucket:
87
Type: AWS::S3::Bucket
88
Properties:
89
BucketName: !Join
90
- '-'
91
- - code-bucket
92
- !Ref AWS::Region
93
- !Select
94
- 0
95
- !Split
96
- '-'
97
- !Select
98
- 2
99
- !Split
100
- '/'
101
- !Ref 'AWS::StackId'
102
AccessControl: Private
103
Tags:
104
- Key: Name
105
Value: !Sub ${AWS::StackName}-S3CodeBucket
106
107
SprerBootEC2:
108
Type: AWS::EC2::Instance
109
DependsOn:
110
- SpringBootSG
111
- PublicSubnet
112
Properties:
113
ImageId: !Ref AMI
114
InstanceType: !Ref InstanceType
115
KeyName: !Ref KeyName
116
NetworkInterfaces:
117
- AssociatePublicIpAddress: true
118
DeviceIndex: 0
119
GroupSet:
120
- !Ref SpringBootSG
121
SubnetId: !Ref PublicSubnet
122
UserData:
123
Fn::Base64: !Sub
124
- |
125
#!/bin/bash
126
sudo yum update -y
127
sudo amazon-linux-extras enable java-openjdk11 -y
128
sudo amazon-linux-extras install java-openjdk11 -y
129
sudo yum install -y java-11-openjdk-devel
130
- {}
131
Tags:
132
- Key: Name
133
Value: !Sub ${AWS::StackName}-SpringBootEC2

The template contains the following resources:

  • VPC: This resource creates a VPC with a CIDR block of 15.0.0.0/16.
  • PublicSubnet: This resource creates a public subnet with a CIDR block of 15.0.0.0/24.
  • IGW: This resource creates an Internet Gateway.
  • VPCGatewayAttachment: This resource attaches the Internet Gateway to the VPC.
  • PublicRouteTable: This resource creates a public route table.
  • PublicRoute: This resource creates a public route.
  • PublicSubnetRouteTableAssociation: This resource associates the public route table with the public subnet.
  • SpringBootSG: This resource creates a security group for the Spring Boot application.
  • S3CodeBucket: This resource creates an S3 bucket to store the Spring Boot application code.
  • SprerBootEC2: This resource creates an EC2 instance to host the Spring Boot application.

Outputs

The next section is the Outputs section. This section is optional and provides information about the stack’s resources.

spring-boot-cloudformation-template-cfn.yaml
1
Outputs:
2
S3CodeBucket:
3
Description: S3 bucket to store the Spring Boot application code
4
Value: !Ref S3CodeBucket
5
SpringBootEC2:
6
Description: Spring Boot EC2 instance
7
Value: !Ref SprerBootEC2
8
SpringBootEC2PublicIP:
9
Description: Spring Boot EC2 instance public IP
10
Value: !GetAtt SprerBootEC2.PublicIp
11
SpringBootEC2PublicDNS:
12
Description: Spring Boot EC2 instance public DNS
13
Value: !GetAtt SprerBootEC2.PublicDnsName

The template contains the following outputs:

  • S3CodeBucket: This output provides the S3 bucket name to store the Spring Boot application code.
  • SpringBootEC2IP: This output provides the IP address of the Spring Boot EC2 instance.

To get the full template, see spring-boot-cloudformation-template-cfn.yaml.

Create the Stack

To create a stack using a CloudFormation template, you can use the AWS Management Console, AWS CLI, or SDKs. Here’s an example of how to create a stack using the AWS CLI:

Terminal window
aws cloudformation create-stack \
--stack-name spring-boot-cloudformation \
--template-body file://spring-boot-cloudformation-template-cfn.yaml \
--parameters ParameterKey=KeyName,ParameterValue=aws-key-pair \
--capabilities CAPABILITY_NAMED_IAM

The command creates a stack:

  • --stack-name: The name of the stack, which is spring-boot-cloudformation.
  • --template-body: The path to the template file, which is spring-boot-cloudformation-template-cfn.yaml.
  • --parameters: The parameters to pass to the template, which is the key pair name aws-key-pair.
  • --capabilities: The capabilities to pass to the template, which is CAPABILITY_NAMED_IAM.

Upload the Spring Boot Application .jar File to the S3 Bucket

First, you need to create a .jar file of the Spring Boot application. To do that, you can use the following command:

Terminal window
mvn clean install
mvn clean package

The command creates a .jar file of the Spring Boot application in the target directory.

Next, you need to upload the .jar file to the S3 bucket. To do that, you can use the following command:

Terminal window
AWS_S3_BUCKET_NAME=$(aws cloudformation describe-stacks \
--stack-name spring-boot-cloudformation \
--query 'Stacks[0].Outputs[?OutputKey==`S3CodeBucket`].OutputValue' \
--output text)
aws s3 cp target/spring-boot-web-0.0.1-SNAPSHOT.jar s3://$AWS_S3_BUCKET_NAME

The command uploads the .jar file to the S3 bucket:

  • AWS_S3_BUCKET_NAME: The name of the S3 bucket, which is the output of the S3CodeBucket output.
  • target/spring-boot-web-0.0.1-SNAPSHOT.jar: The path to the .jar file, which is the .jar file of the Spring Boot application.

Connect to the EC2 Instance

To connect to the EC2 instance, you need to get the public IP address of the EC2 instance. To do that, you can use the following command:

Terminal window
AWS_EC2_PUBLIC_IP=$(aws cloudformation describe-stacks \
--stack-name spring-boot-cloudformation \
--query 'Stacks[0].Outputs[?OutputKey==`SpringBootEC2PublicIP`].OutputValue' \
--output text)
ssh -i ~/.ssh/aws-key-pair.pem ec2-user@$AWS_EC2_PUBLIC_IP

The command connects to the EC2 instance:

  • AWS_EC2_PUBLIC_IP: The public IP address of the EC2 instance, which is the output of the SpringBootEC2PublicIP output.
  • ~/.ssh/aws-key-pair.pem: The path to the key pair file.

Spring Boot CloudFormation EC2 Instance

Run the Spring Boot Application

Get the .jar file from the S3 bucket:

Terminal window
aws s3 ls
# copy the bucket name from the output
aws s3 cp s3://<bucket-name>/spring-boot-web-0.0.1-SNAPSHOT.jar .

The command gets the .jar file from the S3 bucket.

Spring Boot CloudFormation S3 Bucket

Run the Spring Boot application:

Terminal window
java -jar spring-boot-web-0.0.1-SNAPSHOT.jar

The command runs the Spring Boot application.

Spring Boot CloudFormation Run Spring Boot Application

Access the Spring Boot Application

To access the Spring Boot application, you need to get the public DNS of the EC2 instance. To do that, you can use the following command:

Terminal window
AWS_EC2_PUBLIC_DNS=$(aws cloudformation describe-stacks \
--stack-name spring-boot-cloudformation \
--query 'Stacks[0].Outputs[?OutputKey==`SpringBootEC2PublicDNS`].OutputValue' \
--output text)

The command gets the public DNS of the EC2 instance.

Open the public DNS in the browser:

Terminal window
open http://$AWS_EC2_PUBLIC_DNS:8080/hello

The command opens the public DNS in the browser.

Spring Boot CloudFormation Access Spring Boot Application

Run the Spring Boot Application as a Service

To run the Spring Boot application as a service, you need to create a service file. To do that, you can use the following command:

Terminal window
sudo vi /etc/systemd/system/spring-boot-web.service
Terminal window
[Unit]
Description=Spring Boot Web
After=network.target
[Service]
User=ec2-user
WorkingDirectory=/home/ec2-user
ExecStart=/usr/bin/java -jar spring-boot-web-0.0.1-SNAPSHOT.jar > /home/ec2-user/spring-boot-web.log 2>&1 &
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target

The command creates a service file.

Reload the daemon:

Terminal window
sudo systemctl daemon-reload

The command reloads the daemon.

Start the service:

Terminal window
sudo systemctl start spring-boot-web

The command starts the service.

Enable the service:

Terminal window
sudo systemctl enable spring-boot-web

The command enables the service.

Check the status of the service:

Terminal window
sudo systemctl status spring-boot-web

The command checks the status of the service.

Spring Boot CloudFormation Run Spring Boot Application as a Service

Delete the Stack

To delete the stack, you can use the following command:

Terminal window
aws cloudformation delete-stack --stack-name spring-boot-cloudformation

The command deletes the stack.

Conclusion

In conclusion, deploying a Spring Boot application to AWS CloudFormation can provide many benefits such as scalability and easy management. By following the steps outlined in this article, you should now have a solid understanding of how to deploy a Spring Boot application to AWS CloudFormation. From creating a CloudFormation template, to packaging the application into a deployable artifact, updating the stack with the new version of the application and setting up continuous deployment, the guide covers all the necessary steps for a successful deployment. Keep in mind that this guide assumes that you have met all the prerequisites and are familiar with the Spring Boot application’s dependencies and configuration. With this knowledge, you should be able to deploy your Spring Boot application to AWS CloudFormation with confidence.

References

Here are some references that you can use to learn more about the topics covered in this article:

Related Posts

Check out some of our other posts

How To Create A Custom VPC Using AWS CLI

How To Create A Custom VPC Using AWS CLI

Introduction In the sample that follows, an IPv4 CIDR block, a public subnet, and a private subnet are all created using AWS CLI instructions. You can run an instance in the public subnet and con

read more
How to Install and Setup FireWall on Amazon Linux 2

How to Install and Setup FireWall on Amazon Linux 2

Introduction We will learn how to install and setup FireWall on Amazon Linux 2 in this tutorial. We will also discover how to set up FireWall so that it functions with the Amazon Linux 2. Pre

read more
How to Install Apache Web Server on Amazon Linux 2

How to Install Apache Web Server on Amazon Linux 2

Introduction In this tutorial, we will learn how to install Apache web server on Amazon Linux 2. We will also learn how to configure Apache web server to run simple HTML web page. Prerequisit

read more
How to Install PHP and MariaDB on Amazon Linux 2

How to Install PHP and MariaDB on Amazon Linux 2

Introduction We will learn how to set up PHP and MariaDB on Amazon Linux 2 in this tutorial. We will also discover how to set up PHP so that it functions with the Apache web server. We will also

read more
How to Install WordPress on Amazon Linux 2

How to Install WordPress on Amazon Linux 2

Introduction We will learn how to install WordPress on Amazon Linux 2 in this tutorial. We will also discover how to set up WordPress so that it functions with the Apache web server. We will also

read more
How To Create An AWS EC2 Instance Using AWS CLI

How To Create An AWS EC2 Instance Using AWS CLI

Introduction We will learn how to create an AWS EC2 instance using AWS CLI in this tutorial. We will also discover how to set up an AWS EC2 instance so that it functions with the Apache web serve

read more