Spring Boot API on Always Free Oracle Cloud

Spring Boot in free cloud virtual machines

In this article, you will find out how to deploy a Spring Boot API on Always Free Oracle Cloud. Finding Always Free virtual machines with reasonable specifications is a common tasks for those who want test environments, develop demos or simply want some simple and free cloud virtual machine. Whatever your intended usage is, the Oracle Cloud Infrastructure (OCI) provides convenient Always Free services which could meet basic needs and the most interesting shape of an ARM based VM with 4 OCPU and 24 GB of RAM.

How to create a free cloud virtual machine on Oracle Cloud

Once you sign in into Oracle Cloud Infrastructure console, you can add a new VM instance. Then, the create compute instance screen asks for the desired options. As stated before, the best free option is the ARM one. Other options available are the image and the virtual cloud network options.

Important considerations:

  • Keep you public and private keys in a safe location
  • Remember to set up you public IP address
  • You can change your operating system image for any of the options for your shape including FreeBSD, Ubuntu, BYOL partner images as well as optimized versions of Oracle Linux for specific shapes (i.e. graphics card based)

The next step is to generate the public and private keys to access your instance via SSH.

SSH connection to a free cloud virtual machine

User opc is the default user for OCI instances and has sudo full sudo privilege. Connection options include remote desktop connections. For SSH connections, save the public and private keys from the create instance screen in a safe location and execute this commands (replacing the key path and public IP address for your values):

chmod 700 PRIVATE_KEY_PATH
ssh -i PRIVATE_KEY_PATH opc@PUBLIC_IP_ADDRESS

After you log into your VM, in most cases it is required to open ports not only in the Virtual Cloud Network but in the operating system firewall. For Oracle Linux, you must execute this commands in order to enable internet connections to your Oracle VM in port 8080 in the OS firewall:

sudo firewall-cmd --zone=public --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

in the OCI console you must enable http (tcp) connections on port 8080. Go to your instance, select your subnet and then select the default security list. Add a new Ingress rule (Stateless, CIDR, source 0.0.0.0/0, protocol tcp and destination port 8080):

Ingress access rules for Spring Boot on port 8080

And that’s it. User opc is the default user for OCI instances and has sudo full sudo privilege and can be used to install new packages.

How to install new software in the VM

Installing software is the same as with an on-premise machine with the same operating system image selected during creation of the VM. For Oracle Linux the command is:

sudo yum install your_package_name

For example, to install the Java JDK 11 in Oracle Linux you can execute:

[opc@instance-20220902-2325 ~]$ sudo yum install jdk-11
Failed to set locale, defaulting to C.UTF-8
Last metadata expiration check: 1:50:05 ago on Sun Sep  4 01:49:00 2022.
Dependencies resolved.
==============================================================================================================================================================================================================================================================================
 Package                                                     Architecture                                                 Version                                                                 Repository                                                             Size
==============================================================================================================================================================================================================================================================================
Installing:
 jdk-11                                                      aarch64                                                      2000:11.0.16.1-ga                                                       ol8_oci_included                                                      141 M

Transaction Summary
==============================================================================================================================================================================================================================================================================
Install  1 Package

Total download size: 141 M
Installed size: 265 M
Is this ok [y/N]: y
Downloading Packages:
jdk-11.0.16.1_linux-aarch64_bin.rpm                                                                                                                                                                                                            26 MB/s | 141 MB     00:05    
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                                                                                          26 MB/s | 141 MB     00:05     
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                                                                                                                                      1/1 
  Installing       : jdk-11-2000:11.0.16.1-ga.aarch64                                                                                                                                                                                                                     1/1 
  Running scriptlet: jdk-11-2000:11.0.16.1-ga.aarch64                                                                                                                                                                                                                     1/1 
  Verifying        : jdk-11-2000:11.0.16.1-ga.aarch64                                                                                                                                                                                                                     1/1 

Installed:
  jdk-11-2000:11.0.16.1-ga.aarch64                                                                                                                                                                                                                                            

Complete!
[opc@instance-20220902-2325 ~]$ 

Spring Boot free cloud virtual machine example

We will expose a simple web API in our recently created server. First, go to Spring Initializr to create an skeleton project. Set Java version 11 and the web dependency.

Spring Initializr and a simple web API project

Unzip your Spring Boot project and modify the SimpleapiApplication.java file:

package com._dev.simpleapi.simpleapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SimpleapiApplication {

    
    public static void main(String[] args) {
        SpringApplication.run(SimpleapiApplication.class, args);
    }

    @GetMapping("/simpleapi/{id}")
    public String ping(@PathVariable Long id) {
        return "Ping "+id;
    }
}

Then you can generate the corresponding local jar file and copy it to your cloud VM with:

./mvnw package
cd target
scp -i your-key-fullpath/your-ssh-key.key simpleapi-0.0.1-SNAPSHOT.jar opc@your_host:/home/opc

With your application deployed, log in with ssh to your VM and run the Spring Boot application:

[opc@instance-20220902-2325 ~]$ java -jar simpleapi-0.0.1-SNAPSHOT.jar 

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.3)

2022-09-04 03:56:02.474  INFO 325800 --- [           main] c._.s.simpleapi.SimpleapiApplication     : Starting SimpleapiApplication v0.0.1-SNAPSHOT using Java 11.0.16.1 on instance-20220902-2325 with PID 325800 (/home/opc/simpleapi-0.0.1-SNAPSHOT.jar started by opc in /home/opc)
2022-09-04 03:56:02.477  INFO 325800 --- [           main] c._.s.simpleapi.SimpleapiApplication     : No active profile set, falling back to 1 default profile: "default"
2022-09-04 03:56:03.285  INFO 325800 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-09-04 03:56:03.297  INFO 325800 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-09-04 03:56:03.297  INFO 325800 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-09-04 03:56:03.359  INFO 325800 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-09-04 03:56:03.360  INFO 325800 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 795 ms
2022-09-04 03:56:03.657  INFO 325800 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-09-04 03:56:03.666  INFO 325800 --- [           main] c._.s.simpleapi.SimpleapiApplication     : Started SimpleapiApplication in 1.575 seconds (JVM running for 1.929)

To test your Spring Boot API you can try the URL in your browser or this command:

curl http://your_public_ip:8080/simpleapi/123

If everything is working correctly, Ping 123 is a proper response when you invoke the API.

Spring Boot API with Oracle Autonomous Always Free database

You can set up your cloud infrastructure and virtual cloud network with your Always Free servers as well as other resources like Oracle Autonomous database Always Free tier but you must consider that in the Always Free tier the database connection can’t be made inside your private VCN so you would have impacts on latency and security (wallet connections).

Oracle, Java, and MySQL are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.


Posted

in

, , , ,

by

Tags: