Kubernetes ConfigMaps and Secrets with Spring Boot

Managing configuration and sensitive data is a crucial part of deploying secure, production-grade microservices. In Kubernetes, ConfigMaps and Secrets allow you to externalize configuration and keep sensitive data out of source code.

In this guide, you’ll learn how to:

  • Create ConfigMaps and Secrets
  • Inject them into a Spring Boot application
  • Access them via environment variables and mounted files
  • Follow best practices for security and flexibility

This tutorial uses a sample Spring Boot app with the package:
com.kscodes.springboot.containers

Kubernetes ConfigMaps and Secrets with Spring Boot

🧰 Prerequisites

  • Kubernetes cluster (Minikube, GKE, EKS, or AKS)
  • Docker image of Spring Boot app
  • kubectl CLI
  • Basic YAML and Spring Boot familiarity

🚀 Step 1: Sample Spring Boot Code

Here’s a basic Spring Boot controller that reads config values.

Make sure your application.properties allows external config override:

🧾 Step 2: Create ConfigMap

You can create a ConfigMap from a file or inline.

Option A: Inline YAML

Option B: From File

Apply if using YAML:

🔐 Step 3: Create Kubernetes Secret

Use base64-encoded data if you’re using YAML.

To create manually:

📦 Step 4: Update Deployment YAML

Here’s how to inject both ConfigMap and Secret into your Spring Boot container:

Apply it:

🧪 Step 5: Test the Setup

Once deployed, access your Spring Boot app:

Use the IP/port or tunnel to access /config:

You should see:

🛡️ Bonus: Mount as Files (Alternative)

You can also mount ConfigMap/Secret as files:

Then read from the mounted file using Spring’s @ConfigurationProperties or directly via file path.

⚙️ Best Practices

PracticeWhy It Matters
Use Secrets for passwords/tokensBase64 encoding adds a layer of safety
Do not commit Secrets to GitUse .gitignore for secret YAMLs
Avoid storing config in the imageKeeps builds reusable and generic
Use RBAC to restrict accessLimit who can read Secrets

📘 Summary

In this guide, you learned how to use Kubernetes ConfigMaps and Secrets with Spring Boot to inject dynamic and sensitive configuration into your containers. You saw how to use both environment variables and file-based mounts, and followed best practices for secure, maintainable deployments.

This is a core building block of 12-factor Spring Boot apps on Kubernetes.