0% found this document useful (0 votes)
28 views10 pages

Deploy Spring Boot on AWS Guide

The document provides instructions for configuring AWS CloudFormation, Elastic Beanstalk, AWS Fargate, Amazon Database Services including DynamoDB, and Elastic Cache. For CloudFormation, the steps include creating an AWS key pair, configuring credentials, defining stack templates, and deploying stacks. For Elastic Beanstalk, it describes uploading code to S3, selecting a machine image, configuring templates, and deploying environments. It also provides sample Fargate templates and deployment steps. For databases, it outlines setting up DynamoDB with Spring Boot and testing, and configuring Elastic Cache with Redis.

Uploaded by

Mousam Bhagat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views10 pages

Deploy Spring Boot on AWS Guide

The document provides instructions for configuring AWS CloudFormation, Elastic Beanstalk, AWS Fargate, Amazon Database Services including DynamoDB, and Elastic Cache. For CloudFormation, the steps include creating an AWS key pair, configuring credentials, defining stack templates, and deploying stacks. For Elastic Beanstalk, it describes uploading code to S3, selecting a machine image, configuring templates, and deploying environments. It also provides sample Fargate templates and deployment steps. For databases, it outlines setting up DynamoDB with Spring Boot and testing, and configuring Elastic Cache with Redis.

Uploaded by

Mousam Bhagat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • AWS CloudFormation Stack Configuration
  • AWS Fargate
  • Amazon Database Services
  • Elastic Cache

AWS

CloudFormation stack Configuration:


1. Create a AWS KeyPair for SSH access in web console and download the
data.
2. Create a new user then you will get private keys, use that credentials for
configuring AWS CLI.
3. Then create a profile with that user credentials to continue.
aws configure –profile demo
Now you need to add all necessary credentials (Access keys)
4. Create a project and the keys downloaded, then add [Link] with all
required configurations like definition of EC2 instance and then security group
definition for that EC2 instance.
 If want docker, need to add that specific definition.
 If want to use RDS, then need to add that specific definition.
5. Then create stack using the [Link] created.
aws cloudformation create-stack –stack-name sample –template-
body [Link] –profile demo –region us-west-2
6. Then run the application required using Docker-compose.
Elastic Beanstalk(EBS):
1. For maven or gradle, make sure the application name is specified
2. Then build & run the project, you will get a jar file.
3. Next step is upload application to S3
aws s3 cp build/libs/[Link] s3://{you
bucket name}/[Link]
4. Using EBS client, Try to get list machine images running and select one
among them.
aws elasticbeanstalk list-available-solution-stacks |grep Java
5. Now start configuring cloudFormation script:
 First basic info:

"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Spring Boot Cloudformation demo stack.",

 Now add parameters:


Specify bucket containing application code:
"Parameters" : {
  "SourceCodeBucket" : {
    "Type" : "String"
  }
}
specify name of application:
"SpringBootApplication": {
  "Type": "AWS::ElasticBeanstalk::Application",
  "Properties": {
    "Description":"Spring boot and elastic beanstalk"
  } }
specify application version:

"SpringBootApplicationVersion": {
  "Type": "AWS::ElasticBeanstalk::ApplicationVersion",
  "Properties": {
    "ApplicationName":{"Ref":"SpringBootApplication"},
    "SourceBundle": {
              "S3Bucket": {"Ref":"SourceCodeBucket"},
              "S3Key": "[Link]"
    }
  }
}

specify configuration template:

"SpringBootBeanStalkConfigurationTemplate": {
  "Type": "AWS::ElasticBeanstalk::ConfigurationTemplate",
  "Properties": {
    "ApplicationName": {"Ref":"SpringBootApplication"},
    "Description":"A display of speed boot application",
    "OptionSettings": [
      {
        "Namespace": "aws:autoscaling:asg",
        "OptionName": "MinSize",
        "Value": "2"
      },
      {
        "Namespace": "aws:autoscaling:asg",
        "OptionName": "MaxSize",
        "Value": "2"
      },
      {
        "Namespace": "aws:elasticbeanstalk:environment",
        "OptionName": "EnvironmentType",
        "Value": "LoadBalanced"
      }
    ],
    "SolutionStackName": "64bit Amazon Linux 2016.09 v2.3.0 running Java 8"
  }
}

Configure Environment properties:

"SpringBootBeanstalkEnvironment": {
  "Type": "AWS::ElasticBeanstalk::Environment",
  "Properties": {
    "ApplicationName": {"Ref":"SpringBootApplication"},
    "EnvironmentName":"JavaBeanstalkEnvironment",
    "TemplateName": {"Ref":"SpringBootBeanStalkConfigurationTemplate"},
    "VersionLabel": {"Ref": "SpringBootApplicationVersion"}
  }
}
6. Now deploy the cloudFormation template:

aws s3 cp [Link] s3://{bucket with


templates}/[Link]

7. Create stack using the above template from s3

aws cloudformation create-stack --stack-name SpringBeanStalk --


parameters ParameterKey=SourceCodeBucket,ParameterValue={bucket
with code} --template-url [Link] with
templates}/[Link]

AWS Fargate:

AWS Fargate is an AWS managed service that is responsible for provisioning and
orchestrating your containerized application. This means that you can deploy hundreds of
containers without having to define any compute resources because the service will do it for
you.

Steps:
 Build the application and build docker image.
 Then push the image to AWS ECR or Dockerhub.

Create login for AWS ECR, then push


$(aws ecr get-login --no-include-email --region us-east-1)
docker build -t jorlugaqui/booksapp . (already performed in previous steps)
docker tag booksapp:latest
[Link]/booksapp:latest
docker push [Link]/booksapp:latest

 Then select compatability launch type as Fargate.


 Define a task in AWS ECS for defining a container.
Similarly, add Task EAM role, size and also container definition.

 Run the task on the default cluster or user-created cluster.


Add Task definition, version of platform, specific cluster, [Link] Tasks & Task groups.
 Check if the application is working.
Use REST API
AWS CloudWatch

Sample Templates:
[Link]
[Link]
[Link]

AMAZON DATABASE SERVICES

For AWS Database usage:


1. First create AWS account
2. Then take necessary subscription to specific DBs.
3. Then choose way of usage either CLI or local or in AWS
4. Then create users and save the keys.
5. Add maven depencies and add necessary config classes.
6. Then add necessary spring annotations which DB specific.
7. Then run the application and test the service.

DynamoDB
Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that
need consistent, single-digit millisecond latency at any scale. It is a fully managed cloud
database and supports both document and key-value store models.

DynamoDB with Springboot :


We can use DynamoDB locally by:
 Direct local installation
 Docker image
 Apache Maven Dependency

Maven Dependencies

<dependency>
  <groupId>[Link]</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
 
<dependency>
  <groupId>[Link]</groupId>
  <artifactId>aws-java-sdk-dynamodb</artifactId>
  <version>1.11.34</version>
</dependency>
 
<dependency>
  <groupId>[Link]</groupId>
  <artifactId>spring-data-dynamodb</artifactId>
  <version>4.5.0</version>
</dependency>

[Link]:
[Link]=[Link]
[Link]=key
[Link]=key2
create DynamoDBConfig class:

Model class:

@DynamoDBTable(tableName = "Book")
public class Book {
    private String id;
    private String name;
    private String price;
    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }
    @DynamoDBAttribute
    public String getName() {
        return name;
    }
    @DynamoDBAttribute
    public String getPrice() {
        return price;
    }
}

Repository Interface:

@EnableScan
public interface BookRepository extends CrudRepository<Book, String> { 
    List<Book> findById(String id);
}
Testing spring application with DynamoDB:
we want to test our application to ensure that we can connect and perform operations
on our local DynamoDB:

Elastic cache
Amazon ElastiCache allows you to seamlessly set up, run, and scale popular open-
Source compatible in-memory data stores in the cloud. Elasticcache has support for two
open-source engines:
 Redis
 Memcached

Elasticcache with Redis:


ElastiCache for Redis is a super fast, in memory, key-value store database.
ElastiCache for Redis is a fully managed service for a standard Redis installation and uses
all the standard Redis APIs
1. Select Amazon Elasticcache cluster as Redis.
2. Make your own Redis shard(configure redis settings)
3. Add VPC(Virtual Private Network Configuration) & security group related
settings
4. Now, Elasticcache will provision and launch the new Redis cluster.  When the
status turns to available the cluster is ready to handle connections.

5. Now you can build your application.

Maven Dependencies:

RedisElasticCache config file:


@Configuration
@EnableCaching
public class RedisConfig {
 
    @Value("${[Link]}")
    private String redisHostName;
 
    @Value("${[Link]}")
    private int redisPort;
 
    @Value("${[Link]}")
    private String redisPrefix;
 
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new
RedisStandaloneConfiguration(redisHostName, redisPort);
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }
 
    @Bean(value = "redisTemplate")
    public RedisTemplate<String, Object>
redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new
RedisTemplate<>();
        [Link](redisConnectionFactory);
        return redisTemplate;
    }
 
    @Primary
    @Bean(name = "cacheManager") // Default cache manager is infinite
    public CacheManager cacheManager(RedisConnectionFactory
redisConnectionFactory) {
        return
[Link](redisConnectionFactory).cacheDefaults(RedisC
[Link]().prefixKeysWith(redisPrefix)).build();
    }
    @Bean(name = "cacheManager1Hour")
    public CacheManager cacheManager1Hour(RedisConnectionFactory
redisConnectionFactory) {
        Duration expiration = [Link](1);
        return [Link](redisConnectionFactory)
                .cacheDefaults([Link]().pre
fixKeysWith(redisPrefix).entryTtl(expiration)).build();
    }
}

[Link]:
[Link]=URL_TO_ELASTIC_CACHE_REDIS_CLUSTER
[Link]=6379
[Link]=testing
Implementing service:
@Cacheable(value = "getLongRunningTaskResult", key="{#seconds}",
cacheManager = "cacheManager1Hour")
public Optional<TaskDTO> getLongRunningTaskResult(long seconds) {
    try {
        long randomMultiplier = new Random().nextLong();
        long calculatedResult = randomMultiplier * seconds;
        TaskDTO taskDTO = new TaskDTO();
        [Link](calculatedResult);
        [Link](2000); // 2 Second Delay to Simulate Workload
        return [Link](taskDTO);
    } catch (InterruptedException e) {
        return [Link](null);
    }
}

Testing:

Common questions

Powered by AI

Deploying a Docker container application using AWS Fargate involves first building the application and creating a Docker image. This image is then pushed to AWS ECR. After logging into AWS ECR, you use commands like 'docker build', 'docker tag', and 'docker push' to manage the image lifecycle. Following this, Fargate is chosen as the compatibility launch type when defining an AWS ECS task. The task definition includes the container details, task execution role, size, and networking configuration. AWS Fargate is suitable for serverless containers because it eliminates the need to manage servers, allowing for automatic scaling without provisioning compute resources, effectively reducing the operational burden for developers .

Amazon ElastiCache supports Redis by providing a fully managed, in-memory data cache that boosts application performance with sub-millisecond query response times. Redis, as an in-memory data structure store, supports strings, hashes, lists, sets, and more, making it versatile for various high-velocity data applications such as caching, session storage, and real-time analytics. ElastiCache manages necessary Redis infrastructure tasks, including nodes' maintenance and software updates, ensuring high availability and automatic failover. This arrangement not only enhances application efficiency due to reduced latency but also scales dynamically with application loads without manual intervention .

To configure AWS CLI with a new user for setting up an AWS CloudFormation stack, you first create a new user on AWS, which provides you with private keys necessary for AWS CLI configuration. Then, you create a configuration profile using the command 'aws configure –profile demo', where you input credentials including access keys obtained from the user creation step. The configuration profile is crucial as it allows you to manage and use multiple sets of credentials, making it easy to switch contexts between different AWS environments or roles within the same environment .

To configure a Redis instance with Amazon ElastiCache, you begin by selecting an ElastiCache cluster configured as Redis, set up Redis shards, and define networking parameters such as VPC and security groups. Once the cluster status is 'available', it is ready for connections. The benefits of using Redis in this setup include its high-speed performance as an in-memory data store and the fully managed nature of ElastiCache, which handles scaling, backups, and failover automatically, letting developers focus on application logic rather than infrastructure management .

In a CloudFormation script for an Elastic Beanstalk application, essential parameters include specifying the S3 bucket containing the application code and the application name. These parameters are included within the script's 'Parameters' section, like 'SourceCodeBucket' for the code and 'SpringBootApplication' for the application name. They are important because they allow the script to automatically reference where the code is stored and associate it correctly within Elastic Beanstalk, ensuring that the correct application version is deployed with the specified configuration template. Incorrect specification can lead to deployment errors or incorrect resource provisioning .

AWS CloudFormation integrates Docker into an EC2 instance through its ability to automate the deployment of infrastructure and applications using templates. In your CloudFormation template, you must include the necessary configurations for the EC2 instance itself and define a security group. To include Docker, the template should incorporate Docker-specific installations or configurations, such as adding Docker software requirements into the EC2's user data section. This approach automates the setup process and ensures that Docker services are correctly installed and configured upon instance creation .

Amazon DynamoDB is a fully managed NoSQL database service known for its fast performance and scalability. Key features include offering consistent, single-digit millisecond latency regardless of scale, supporting both document and key-value store models. DynamoDB automatically manages infrastructure, includinghardware provisioning, setup, configuration, replication, and partitioning across multiple regions. This makes it suitable for applications needing predictable performance and reliability, such as real-time data access services or gaming applications .

AWS Elastic Beanstalk simplifies the deployment, scaling, and management of applications by abstracting environment configurations and deployment tasks. It automates environment provisioning, from resource load balancing to monitoring and application version management. Users can deploy directly from source code, with the platform handling infrastructure complexity. Elastic Beanstalk's integration with AWS services allows it to provide extensive configuration options via templates, supporting various frameworks and languages. Its significance lies in reducing operational overhead, enabling developers to focus on code without the necessity of managing the underlying infrastructure .

AWS CloudFormation offers significant advantages for infrastructure as code (IaC) through its ability to model and set up AWS resources automatically using JSON or YAML templates. The primary benefits include consistent resource configurations, automated provisioning, and accelerated deployment processes, allowing for efficient environment reproducibility across development, staging, and production setups. CloudFormation simplifies complex dependencies, mitigates the risk of manual configuration errors, and provides a centralized method for managing and auditing AWS resources and configurations. These capabilities enhance operational efficiency and enforce best practices in the deployment and management of infrastructure .

When setting up a Maven-based project to utilize AWS services, you start by adding necessary Maven dependencies in the project's POM file. These can include dependencies for spring-boot-starter-web for web development, aws-java-sdk for AWS service interactions, or specific SDKs like aws-java-sdk-dynamodb for DynamoDB access. These dependencies import required libraries and configurations, streamlining the development process by managing versioning and compatibility. Including these dependencies is crucial as they facilitate the integration of AWS services into the project, enabling API interactions and service configurations via Java code .

AWS
CloudFormation stack Configuration:
1.
Create a AWS KeyPair for SSH access in web console and download the 
data.
2.
Crea
specify application version:
"SpringBootApplicationVersion": {
  "Type": "AWS::ElasticBeanstalk::ApplicationVersion",
  "Prop
6.
Now deploy the cloudFormation template:
aws s3 cp beanstalkspring.template s3://{bucket with 
templates}/beanstalkspring.t
Similarly, add Task EAM role, size and also container definition.

Run the task on the default cluster or user-created clust
https://raw.githubusercontent.com/jasonumiker/nginx-codebuild/master/fargate- (https://raw.githubusercontent.com/jasonumiker/
create DynamoDBConfig class:
Model class:
@DynamoDBTable(tableName = "Book")
public class Book {
    private String id;
    p
Testing spring application with DynamoDB:
we want to test our application to ensure that we can connect and perform operation
3.
Add VPC(Virtual Private Network Configuration) & security group related 
settings
4.
Now, Elasticcache will provision and
@Configuration
@EnableCaching
public class RedisConfig {
 
    @Value("${redis.hostname}")
    private String redisHostName;
@Cacheable(value = "getLongRunningTaskResult", key="{#seconds}", 
cacheManager = "cacheManager1Hour")
public Optional<TaskDTO

You might also like