Kubernetes using Cloud Shell: Deploy a Spring Boot Application

In this tutorial, you use an Oracle Cloud Infrastructure account to set up a Kubernetes cluster. Then, you deploy a Spring Boot application to your cluster. Key tasks include how to:

  • Set up an authentication token.
  • Set up a Kubernetes cluster on OCI.
  • Build a Spring Boot application and Docker image.
  • Push your image to OCIR.
  • Deploy your Docker application to your cluster using Cloud Shell.
  • Connect to your application from the internet.
A diagram of the components needed to run a Spring Boot app on Oracle Cloud Infrastructure Container Engine

For additional information, see:

1. Gather Required Information

Prepare the information you need from the Oracle Cloud Infrastructure Console.

  1. Check your service limits:
    • Regions: minimum 2

      In the top navigation bar, expand <region>. Example: US East (Ashburn) and US West (Phoenix).

    • Compute instances: minimum 3

      Click your profile avatar. Select Tenancy. Go to Service Limits and expand Compute.

    • Block Volume: minimum 50 GBs

      In the Service Limits section, expand Block Volume.

    • Load Balancer: available

      In the Service Limits section, expand Networking.

  2. Have a compartment for your cluster.
  3. Create an authorization token:
    • In the top navigation bar, click your user avatar.
    • Select your username.
    • Click Auth Tokens.
    • Click Generate Token.
    • Give it a description.
    • Click Generate Token.
    • Copy the token and save it.
    Note

    Make sure you save your token right after you create it. You will not have access to it later.
  4. Find your region identifier and region key from Regions and Availability Domains. Example: us-ashburn-1 and iad for Ashburn.
  5. Collect the following information and copy them into your notepad.
    • Auth Token: <auth-token> from step 3.
    • Region: <region-identifier> from step 4. Example: us-ahburn-1.
    • Region Key: <region-key> from step 4. Example: iad.
    • Tenancy name: <tenancy-name> from your user avatar.
    • Tenancy OCID: <tenancy-ocid> from your user avatar, go to Tenancy:<your-tenancy> and copy OCID.
    • Username: <user-name> from your user avatar.
    • User OCID: <user-ocid> from your user avatar, go to User Settings and copy OCID.

2. Create SSH Encryption Keys

Create ssh encryption keys you can use to log into your VM.

  1. Open a terminal window:
    • MacOS or Linux: Open a terminal window in the directory where you want to store your keys.
    • Windows: Right click on the directory where you want to store your keys and select Git Bash Here.
  2. Issue the following OpenSSH command:
    ssh-keygen -t rsa -N "" -b 2048 -C <my-key> -f <my-key>

    The command generates some random text art used to generate the keys. When complete, you should have two files:

    • The private key file: <my-key>
    • The public key file: <my-key>.pub

    You use these files to connect to your Compute instance.

You have generated the required encryption keys.

See Creating a Key Pair for more detailed information on generating ssh encryption keys.

3. Create your Virtual Cloud Network (VCN)

Setup a VCN to connect your Linux instance to the internet. You configure all the components needed to create your virtual network.

  1. From the main landing page, select Set up a network with a wizard. Quick action menu from the main Free Tier landing page
  2. In the Start VCN Wizard workflow, select VCN with Internet Connectivity and then click Start VCN Wizard .
  3. In the configuration dialog, fill in the VCN Name for your VCN. Your Compartment is already set to its default value of <your-tenancy> (root).
  4. In the Configure VCN and Subnets section, keep the default values for the CIDR blocks:
    • VCN CIDR BLOCK: 10.0.0.0/16
    • PUBLIC SUBNET CIDR BLOCK: 10.0.0.0/24
    • PRIVATE SUBNET CIDR BLOCK: 10.0.1.0/24
    Note

    Notice the public and private subnets have different network addresses.
  5. For DNS RESOLUTION uncheck USE DNS HOSTNAMES IN THIS VCN.Picture shows the USE DNS HOSTNAMES IN THIS VCN option is unchecked.
  6. Click Next.

    The Create a VCN with Internet Connectivity configuration dialog is displayed (not shown here) confirming all the values you just entered.

  7. Click Create to create your VCN.

    The Creating Resources dialog is displayed (not shown here) showing all VCN components being created.

  8. Click View Virtual Cloud Network to view your new VCN.

    Your new VCN is displayed. Now you need to add a security rule to allow HTTP connections on port 8080, the default port for your application.

  9. With your new VCN displayed, click your Public subnet link.

    The public subnet information is displayed with the Security Lists at the bottom of the page. There should be a link to the Default Security List for your VCN.

  10. Click on the Default Security List link.

    The default Ingress Rules for your VCN are displayed.

  11. Click Add Ingress Rules.

    An Add Ingress Rules dialog is displayed.

  12. Fill in the ingress rule with the following information. Once all the data is entered, click Add Ingress Rules.

    Fill in the ingress rule as follows:

    • Stateless: Checked
    • Source Type: CIDR
    • Source CIDR: 0.0.0.0/0
    • IP Protocol: TCP
    • Source port range: (leave-blank)
    • Destination Port Range: 8080
    • Description: VCN for applications

    Once you click Add Ingress Rule, HTTP connections are allowed to your public subnet.

Note

To open a different port, replace 8080 in the last step with the port number.
You have successfully created a VCN that will make your applications available from the internet.

4. Install your Oracle Linux VM

Install your Oracle Linux VM to host your applications. This is a Free Tier VM and using it is free, no cost forever.
  1. Open the Oracle Cloud Infrastructure main menu.
  2. Select Compute then Instances.
  3. From the list of instances screen click Create Instance.

    The Create Compute Instance dialog is displayed. Notice the Show Shape, Network and Storage Options should be expanded to configure the virtual machine.

  4. Fill in the fields for the Create Compute Instance dialog with the following data:

    Initial Options

    • Name of your Instance: <name-for-the-instance>
    • Choose an Operating System: Oracle Linux 7.8
    • Availability Domain: <select-a-domain>
    • Instance Shape: VM.Standard.E2.1.Micro: Virtual Machine, 1 core OCPU, 1 GB Memory, 0.48 Gbps network bandwidth (the default)
    Note

    To set Instance Shape, from the Shape Series options, you must select Specialty and Legacy. Then you can select VM.Standard.E2.1.Micro. If you want to use this VM for other applications, make sure that the 1GB of memory is adequate for your applications.

    Configure Networking

    • VIRTUAL CLOUD NETWORK COMPARTMENT: <your-compartment>
    • VIRTUAL CLOUD NETWORK: <VCN-you-created>
    • SUBNET COMPARTMENT: <your-subnet-compartment>
    • SUBNET: <public-subnet-you-created>
    • USE NETWORK SECURITY GROUPS TO CONTROL TRAFFIC: Unchecked
    • ASSIGN A PUBLIC IP ADDRESS: Selected/Checked

    Additional Options

    • Boot Volume: All options Unchecked
    • Add SSH Keys: Add the public key file you created in part 1 of this tutorial.
  5. Click Create to create the instance. Provisioning the system may take several minutes.
You have successfully created an Oracle Linux VM to build and test your application.

5. Configure your Oracle Linux VM

Next, configure your VM so you can build and deploy the your application image to Oracle Cloud Infrastructure Registry (OCIR).

Follow these steps to setup your VM so you can build your application:

  1. From the main menu select Compute then Instances.
  2. Click on the link to the instance you just created in the previous step.

    From the Instance Details page look under the Instance Access section. Write down the public IP address the system created for you. You use this IP address to connect to your instance.

  3. Open a Terminal or Command Prompt window.
  4. Change into the directory where you stored the ssh encryption keys you created in part 1.
  5. Connect to your VM with this ssh command
    ssh -i <your-private-key-file> opc@<x.x.x.x>

    Since you identified your public key when you created the VM, this command should log you into your VM. You can now issue sudo commands to install and start your server.

  6. Enable HTTP connection via port 8080.
    $ sudo firewall-cmd --permanent --add-port=8080/tcp
    success
    $ sudo firewall-cmd --reload

Install Git

Install Git v2 using the IUS Community Project (https://ius.io/) Spring Boot Docker tutorial. Navigate to the current version of Git core package and download to a ~/temp directory. For example, installing the Git 2.2.4 core package looks like this.

  1. For example, downloading the Git RPM might looks like this.
    
    cd
    mkdir temp
    cd ~/temp
    wget https://repo.ius.io/7/x86_64/packages/g/git224-core-2.24.2-1.el7.ius.x86_64.rpm                        
                        

    The wget command saves the Git package to the temp directory.

  2. Install the RPM with yum.
    
    sudo yum install git224-core-2.24.2-1.el7.ius.x86_64.rpm
                        
  3. Test result.
    
    git --version
    git version 2.24.2
                        

    Git is installed.

Install JDK 8

  1. Install OpenJDK 8 using yum.
    sudo yum install java-1.8.0-openjdk-devel
    java -version
  2. Set JAVA_HOME in .bashrc.

    Update the file:

    vi ~/.bashrc

    In the file, append the following text and save the file:

    # set JAVA_HOME
    export JAVA_HOME=/etc/alternatives/java_sdk

    Activate the above command in the current window.

    source ~/.bashrc

Install Maven 3.6

Install Maven from an Apache mirror. Go to the main Maven site's (https://maven.apache.org/) download page. Get the the URL for the latest version and download with wget.

  1. Download the Maven zip file.
    
    wget http://apache.mirrors.pair.com/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz                                    
  2. Extract the program files.
    
    sudo tar xvfz apache-maven-3.6.3-bin.tar.gz
                        
  3. Install the program files by moving the files to the /opt directory.
    
    sudo mv apache-maven-3.6.3 /opt/
                        
  4. Add the Maven path /opt/apache-maven-3.6.3/bin to your PATH environment variable and source your .bashrc.
    
    vi ~/.bashrc
    export PATH=$PATH:/opt/apache-maven-3.6.3/bin
    source ~/.bashrc
                        

    Maven should now be ready to use.

Build Your Spring Boot Application

Now, build your Spring Boot application.

  1. Check out the Spring Boot Docker guide with Git:
    git clone http://github.com/spring-guides/gs-spring-boot-docker.git
  2. Change into the gs-spring-boot-docker/initial directory.
  3. Edit the Application.java file: src/main/java/hello/Application.java.
  4. Update the code with the following:
    
    package hello;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
        @SpringBootApplication
        @RestController
        public class Application {
    
            @RequestMapping
            public String home(){
                return "<h1>Spring Boot Hello World!</h1>";
            }
            
            public static void main(String[] args) {
                SpringApplication.run(Application.class, args);
            }
    
    }
                        
  5. Save the file.
  6. Use Maven to build the application.
    mvn package

    You should get a message of success.

    [INFO] BUILD SUCCESS
  7. Run the application.
    java -jar target/gs-spring-boot-docker-0.1.0.jar
  8. Test your application from the command line or a browser.
    • From a new terminal, connect to your VM with your SSH keys and test with curl:
      curl -X GET http://localhost:8080
      .
    • From your browser connect to the public IP address assigned to your VM: http://<x.x.x.x>:8080.

    You should see Spring Boot Hello World! on your VM or in your browser.

Congratulations! You have successfully created a Spring Boot application on your VM.

6. Build and Push your Spring Boot Application

Next, install Docker and build your Docker image so you can deploy the image to Oracle Cloud Infrastructure Registry (OCIR).

Install Docker

Install Docker on your Oracle Linux VM.

  1. Install the Docker packages for Oracle Linux.
    
    sudo yum install docker-engine docker-cli                        
                        
  2. Start the docker service and configure it to start at boot time.
    
    sudo systemctl enable --now docker                        
                        
  3. Check if the Docker service is running.
    
    sudo systemctl status docker                        
                        
  4. Check your Docker configuration.
    
    sudo docker info                        
                        

Build your Docker Image

Build a Docker image for your application.

  1. First, make sure you are in the gs-spring-boot-docker/initial directory.
  2. Create a file named Dockerfile.
    
    FROM openjdk:8-jdk-alpine
    RUN addgroup -S spring && addduser -S spring -G spring
    USER spring:spring
    ARG JAR_FILE=target/*.jar
    COPY ${JAR_FILE} app.jar
    ENTRYPOINT ["java","-jar","/app.jar"]
                        
  3. Build the Docker image: sudo docker build -t spring-boot-hello .
  4. Run your Docker image: sudo docker run -p 8080:8080 -t spring-boot-hello
  5. Test the application using the command line or a browser.
    • To test with curl, in a terminal run: curl -X GET http://localhost:8080
    • Connect your browser to the public IP address assigned to your VM: http://<x.x.x.x>:8080.

    Your Docker environment is now setup for OCIR.

    For more information, see the Spring Boot Docker tutorial.

Push your Docker image to OCIR

With your Docker image created, now you need to push it to OCIR.

  1. Open a terminal window.
  2. Log Docker into OCIR:
    sudo docker login <region-key>.ocir.io

    You are prompted for your login name and password.

    • Username: <tenancy-name>/<user-name>
    • Password: <auth-token>
  3. List your local Docker images.
    sudo docker images

    The Docker images on your system are displayed. Identify the image you created in the last section: spring-boot-hello

  4. Tag your local image so it can be pushed to OCIR:
    sudo docker tag <your-local-image> <target-tag>

    The target tag consists of: <region-key>.ocir.io/<tenancy-name>/<image-folder>/<image-name>

    Example: sudo docker tag spring-boot-hello iad.ocir.io/<tenancy-name>/<image-folder>/spring-boot-hello

    Note

    The image-folder is a string of your choosing that is used to group your images. For example, a short version of your username is often used. "John Doe" might use: sudo docker tag spring-boot-hello iad.ocir.io/<tenancy-name>/johnd/spring-boot-hello.
  5. Check your Docker images to see if the tag has been created.
    sudo docker images

    The target tag that you created should have the same image ID as your local image.

  6. Push the image to OCIR.
    sudo docker push <target-tag>:latest>

    Example: sudo docker push iad.ocir.io/<tenancy-name>/<image-folder>/spring-boot-hello:latest

    You should see your image in OCIR after the push command is complete.

View the OCIR Repository you Created

  1. From the main menu select Developer Services, then Registry.
  2. Navigate to the repository you created: <image-folder>/<image-name>:latest.
  3. By default your repository is created with private access.
Congratulations! You have successfully created a Spring Boot Docker image.

7. Create your Kubernetes Cluster

Set up the Kubernetes cluster you will deploy your application to. You will use a wizard to set up your first cluster.

  1. From the OCI main menu select Developer Services then Container Clusters.
  2. Click Create Cluster.
  3. Select Quick Create.
  4. Click Launch Workflow.

    The Cluster Creation dialog is displayed.

  5. Fill in the following information:
    • Name: <your-cluster-name>
    • Compartment: <your-compartment-name>
    • Kubernetes Version: <take-default>
    • Visibility Type: <Private>
    • Shape: VM.Standard.E2.1
    • Number of Nodes: 3
    • Add Ons: <none-selected>
  6. Click Next.

    All your choices are displayed. Review them to make sure everything is configurated correctly.

  7. Click Create Cluster.

    The services set up for your cluster are displayed.

  8. Click Close.
  9. Get a cup of coffee. It may take a few minutes for the cluster to be created.
You have successfully created a Kubernetes cluster.

8. Manage your Kubernetes Cluster with Cloud Shell

With your Kubernetes cluster setup, you need to configure your Cloud Shell instance. To do that, complete the following steps:

  1. From the OCI main menu select Developer Services then Container Clusters.
  2. Click the link to <your-cluster>.

    The information about your cluster is displayed.

  3. Click Access Cluster.
  4. Select Cloud Shell Access.
  5. Follow the steps provided in the dialog. They are reprinted here for your reference.
    Note

    All the required tools are installed in your cloud shell environment.

    Open your Cloud Shell environment.

    Make your .kube directory if it doesn't exist.

    mkdir -p $HOME/.kube

    Create kubeconfig file for your setup. Use the information from Access Your Cluster dialog.

    oci ce cluster create-kubeconfig <copy-data-from-dialog>
  6. Test your cluster configuration with the following commands.

    List clusters:

    kubectl get service
    Note

    If you have existing clusters, the new cluster information is merged with your $HOME/.kube/config file.

With your cluster configured, you are now ready to prepare your application for deployment.

9. Deploy your Docker Image to your Cluster with Cloud Shell

With your cluster ready, use cloud shell to deploy your application.

Create a Secret to Securely Connect to OCIR

  1. First, create a registry secret for your application. This will be used to authenticate your image when it is deployed to your cluster.

    Fill in the information in this template to create your secret.

    
    kubectl create secret docker-registry ocirsecret --docker-server=<region-key>.ocir.io  --docker-username='<tenancy-name>/<user-name>' --docker-password='<auth-token>'  --docker-email='<email-address>'                                
                    

    After executing the command, you should get a message similar to: secret/ocirsecret created.

  2. Verify the secret was created. Issue the following command.
    kubectl get secret ocirsecret --output=yaml

    The output includes information about your secret is shown in the yaml format.

Create a Manifest file and Deploy your Image

With your image in OCIR, you can now deploy your image and app.

  1. From the home directory, create a directory called spring-hello.
    mkdir spring-hello
  2. Change to the spring-hello directory.
    cd spring-hello
  3. Determine the host URL to your registry image using the following template.
                            <region-code>.ocir.io/<tenancy-name>/<image-directory>/<image-name>:<tag>
  4. Create a file called sb-app.yaml.
    
                            vi sb-app.yaml
  5. Copy the following information in your sb-app.yaml.
    Note

    Your code must have the exact same indentation. The deployment and load balancer service are separated with ---.

    Here are some of the parameters that you will set for the deployment section:

    • replicas: 3
    • image: <your-image-url>
    • imagePullPolicy: Always
    • protocol: TCP
    • imagePullSecrets:
      • name: ocirsecret
    
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: sbapp
    spec:
      selector:
        matchLabels:
          app: sbapp
      replicas: 3
      template:
        metadata:
        labels:
          app: sbapp
        spec:
          containers:
          - name: sbapp
            image: <your-image-url>
            imagePullPolicy: Always
            ports:
            - name: sbapp
            containerPort: 8080
            protocol: TCP
          imagePullSecrets:
          - name: <your-secret-name>
    ---
    apiVersion: v1
    kind: Service
      metadata:
      name: sbapp-lb
        labels:
          app: sbapp
    spec:
      type: LoadBalancer
      ports:
      - port: 8080
        selector:
          app: sbapp
                        

    Note: The code after the dashes adds a load balancer.

  6. Deploy your application with the following command.
    kubectl create -f sb-app.yaml
Test your App

Your load balancer may take a few seconds to load after issuing the command.

  1. Check for your load balancer to deploy.
    kubectl get service

    Repeat the command until load balancer is assigned an IP address.

  2. Using the IP address for the load balancer connect to your app in a browser, http://x.x.x.x:8080
Clean up your App

After you are done, cleanup and remove the services you created.

  1. Delete your app and load balancer.
    kubectl delete -f sbapp.yaml

    The following messages are returned:

    
    service "sbapp-lb" deleted
    deployment.extensions "sbapp" deleted
                        

    To check that the service is removed:

    kubectl get service
Congratulations! You have successfully installed and deployed a Spring Boot app to a Kubernetes cluster on Oracle Cloud Infrastructure.

What's Next

You have successfully created a Hello World application, deployed it to a Kubernetes cluster and made it accessible on the internet, using Spring Boot.

To explore more information about development with Oracle products check out these sites: