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

  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Spring Boot With Kubernetes
  • Containerization and Helm Templatization Best Practices for Microservices in Kubernetes
  • Messaging With Spring Boot and Azure Service Bus

Trending

  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • The Evolution of Scalable and Resilient Container Infrastructure
  • Implementing Explainable AI in CRM Using Stream Processing
  • Designing a Java Connector for Software Integrations
  1. DZone
  2. Coding
  3. Frameworks
  4. Configuring Spring Boot on Kubernetes With ConfigMap

Configuring Spring Boot on Kubernetes With ConfigMap

See how you can configure your Spring Boot apps on Kubernetes clusters by using ConfigMaps and your properties files for better portability.

By 
Kamesh Sampath user avatar
Kamesh Sampath
·
Oct. 05, 17 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
68.3K Views

Join the DZone community and get the full member experience.

Join For Free

ConfigMaps is the Kubernetes counterpart of the Spring Boot externalized configuration. ConfigMaps is a simple key/value store, which can store simple values to files. In this post, we will see how to use ConfigMaps to externalize application configuration.

One way to configure Spring Boot applications on Kubernetes is to use ConfigMaps. ConfigMaps is a way to decouple the application-specific artifacts from the container image, thereby enabling better portability and externalization.

The sources of this blog post are available in my GitHub repo. In this blog post, we will build simple GreeterApplication, which exposes a REST API to greet the user. The GreeterApplication will use ConfigMaps to externalize the application properties.

You may also enjoy Linode's Beginner's Guide to Kubernetes.

Setup

You might need access to a Kubernetes cluster to play with this application. The easiest way to get a local Kubernetes cluster up and running is using minikube.The rest of the blog assumes you have minikube up and running.

There are two ways to use ConfigMaps:

  1. ConfigMaps as Environment variables
  2. Mounting ConfigMaps as files

ConfigMaps as Environment Variables

Assuming you have cloned my GitHub repo, let’s refer to the cloned location of the source code as $PROJECT_HOME throughout this document.

You will notice that com.redhat.developers.GreeterController has code to look up an environment variable GREETER_PREFIX.

package com.redhat.developers;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@Slf4j
public class GreeterController {
 
    @Value("${greeter.message}")
    private String greeterMessageFormat; 
 
    @GetMapping("/greet/{user}")
    public String greet(@PathVariable("user") String user) {
        String prefix = System.getenv().getOrDefault("GREETING_PREFIX", "Hi");
        log.info("Prefix :{} and User:{}", prefix, user);
        if (prefix == null) {
            prefix = "Hello!";
        }
 
        return String.format(greeterMessageFormat, prefix, user);
    }
}


By convention, Spring Boot applications — rather, Java applications — pass these kinds of values via system properties. Let us now see how we can do the same with a Kubernetes deployment.

  • Let’s create a Kubernetes ConfigMaps to hold the property called greeter.prefix, which will then be injected into the Kubernetes deployment via an environment variable called GREETER_PREFIX.

Create ConfigMap

kubectl create configmap spring-boot-configmaps-demo --from-literal=greeter.prefix="Hello"


  • You can see the contents of the ConfigMap using the command: kubectl get configmap spring-boot-configmaps-demo-oyaml

Create Fragment deployment.yaml

Once we have the Kubernetes ConfigMaps created, we then need to inject the GREETER_PREFIX as an environment variable into the Kubernetes deployment. The following code snippet shows how to define an environment variable in a Kubernetes deployment.yaml.

spec:
  template:
    spec:
      containers:
        - env:
          - name: GREETING_PREFIX
            valueFrom:
             configMapKeyRef:
                name: spring-boot-configmaps-demo
                key: greeter.prefix


  • The above snippet defines an environment variable called GREETING_PREFIX, which will have its value set from the ConfigMap spring-boot-configmaps-demo key greeter.prefix.

NOTE: As the application is configured to use fabric8-maven-plugin, we can create a Kubernetes deployment and service as fragments in ‘$PROJECT_HOME/src/main/fabric8’. The fabric8-maven-plugin takes care of building the complete Kubernetes manifests by merging the contents of the fragment(s) from ‘$PROJECT_HOME/src/main/fabric8’ during deployment.

Deploy Application

To deploy the application, execute the following command from the $PROJECT_HOME ./mvnw clean fabric8:deploy.

Access Application

The application status can be checked with the command kubectl get pods -w . Once the application is deployed, let’s do a simple curl like:

curl $(minikube service spring-boot-configmaps-demo --url)/greet/jerry; echo "";

The command will return the message, "Hello jerry! Welcome to Configuring Spring Boot on Kubernetes!" The return message has a prefix called “Hello”, which we had injected via the environment variable GREETING_PREFIX with the value from the ConfigMap property “greeter.prefix”.

Mounting ConfigMaps as Files

Kubernetes ConfigMaps also allows us to load a file as a ConfigMap property. That gives us an interesting option of loading the Spring Bootapplication.properties via Kubernetes ConfigMaps.

To be able to load application.properties via ConfigMaps, we need to mount the ConfigMaps as the volume inside the Spring Boot application container.

Update application.properties

greeter.message=%s %s! Spring Boot application.properties has been mounted as volume on Kubernetes!


Create ConfigMap from File

kubectl create configmap spring-app-config --from-file=src/main/resources/application.properties


The command above will create a ConfigMap called spring-app-config with the application.properties file stored as one of the properties.

The sample output of kubectl get configmap spring-app-config -o yaml is shown below.

apiVersion: v1
data:
  application.properties: greeter.message=%s %s! Spring Boot application.properties has been mounted as volume on Kubernetes!
    on Kubernetes!
kind: ConfigMap
metadata:
  creationTimestamp: 2017-09-19T04:45:27Z
  name: spring-app-config
  namespace: default
  resourceVersion: "53471"
  selfLink: /api/v1/namespaces/default/configmaps/spring-app-config
  uid: 5bac774a-9cf5-11e7-9b8d-080027da6995
Modifying GreeterController


Modifying GreeterController

package com.redhat.developers;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@Slf4j
public class GreeterController {
 
    @Value("${greeter.message}")
    private String greeterMessageFormat; 
 
    @GetMapping("/greet/{user}")
    public String greet(@PathVariable("user") String user) {
        String prefix = System.getenv().getOrDefault("GREETING_PREFIX", "Hi");
        log.info("Prefix :{} and User:{}", prefix, user);
        if (prefix == null) {
            prefix = "Hello!";
        }
 
        return String.format(greeterMessageFormat, prefix, user);
    }
}


Update Fragment deployment.yaml

Update the deployment.yaml to add the volume mounts that will allow us to mount the application.properties file under /deployments/config.

spec:
  template:
    spec:
      containers:
        - env:
          - name: GREETING_PREFIX
            valueFrom:
             configMapKeyRef:
                name: spring-boot-configmaps-demo
                key: greeter.prefix
          volumeMounts:
          - name: application-config 
            mountPath: "/deployments/config" 
            readOnly: true
      volumes:
      - name: application-config
        configMap:
          name: spring-app-config 
          items:
          - key: application.properties 
            path: application.properties


Let’s deploy and access the application like we did earlier, but this time, the response will be using the application.properties from our ConfigMaps.

In this Part 1 of our blog series, we saw how to configure Spring Boot on Kubernetes with ConfigMaps. In the Part 2, we will see on how to use Kubernetes Secrets to configure Spring Boot applications.

Kubernetes Spring Framework Spring Boot application

Published at DZone with permission of Kamesh Sampath, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Spring Boot With Kubernetes
  • Containerization and Helm Templatization Best Practices for Microservices in Kubernetes
  • Messaging With Spring Boot and Azure Service Bus

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!