<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thejani Mallawaarachchi on Medium]]></title>
        <description><![CDATA[Stories by Thejani Mallawaarachchi on Medium]]></description>
        <link>https://medium.com/@thejani.mallawaarachchi?source=rss-9ddc43bccb4b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tZjWOEQuE2zqutT1Pc2MBg.jpeg</url>
            <title>Stories by Thejani Mallawaarachchi on Medium</title>
            <link>https://medium.com/@thejani.mallawaarachchi?source=rss-9ddc43bccb4b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:09:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thejani.mallawaarachchi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Code to Container: Containerizing Spring Boot Application with Docker & MySQL]]></title>
            <link>https://medium.com/@thejani.mallawaarachchi/from-code-to-container-containerizing-spring-boot-application-with-docker-mysql-be1642659afa?source=rss-9ddc43bccb4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1642659afa</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-spring-boot]]></category>
            <category><![CDATA[docker-mysql]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Thejani Mallawaarachchi]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 18:11:29 GMT</pubDate>
            <atom:updated>2025-09-05T20:16:27.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hs6mzm7sW6Aw4UM69QtQZg.png" /></figure><p>You spend weeks building a microservice, and everything works perfectly on your laptop. But the moment you share it with a teammate or try to run it on a server, errors appear out of nowhere. The dreaded phrase <em>“But it worked on my machine!”</em> echoes once again.</p><p>This is the exact problem Docker was designed to solve. By packaging your application and its dependencies into a single, consistent container, Docker ensures it runs the same way, no matter where you deploy it.</p><h4>🛠️ What Does “Deployment” Actually Mean?</h4><p>In software development, <strong>deployment</strong> simply means the act of making your application available for others to use. It’s the transition from <em>code on your local machine</em> to <em>a running service that others can access</em>.</p><p>Traditionally, deployment involved setting up servers, configuring environments, and resolving dependency or version conflicts. With <strong>Docker</strong>, everything runs inside a container, making deployment fast, consistent, and hassle-free.</p><h4>🐳 What is Docker Deployment?</h4><p><strong>Docker deployment</strong> is the process of packaging your application into a <strong>Docker container</strong> and running it anywhere — on your local machine, a server, or in the cloud.</p><p>A <strong>Docker container</strong> is like a lightweight, portable box that includes:</p><ul><li>Your application code</li><li>Dependencies (libraries, runtimes, configurations)</li><li>A consistent runtime environment</li></ul><p>This ensures that if your app runs in Docker on your laptop, it will run exactly the same on any other environment — eliminating the dreaded <em>“works on my machine”</em> problem.</p><h4>✅ Advantages of Docker Deployment</h4><ul><li><strong>Consistency Across Environments</strong><br>Your application runs the same way everywhere.</li><li><strong>Portability</strong><br>Build once, run anywhere: local machines, cloud providers like AWS or GCP, or on-premise servers.</li><li><strong>Scalability</strong><br>Easily run multiple instances of a service by starting more containers.</li><li><strong>Isolation</strong><br>Each microservice runs in its own container environment, avoiding dependency conflicts.</li><li><strong>Faster Deployment Cycles</strong><br>Containers start in seconds, enabling smoother CI/CD pipelines.</li></ul><h4>⚖️ Disadvantages (Things to Watch Out For)</h4><ul><li><strong>Learning Curve</strong><br>Docker introduces concepts like images, containers, volumes, and networks, which can be overwhelming for beginners.</li><li><strong>Performance Overhead</strong><br>Containers are lightweight compared to virtual machines, but they still introduce a small performance cost.</li><li><strong>Security Risks</strong><br>Exposing containers to the internet without proper configuration can create vulnerabilities.</li><li><strong>Persistence Complexity</strong><br>Containers are ephemeral by nature, so managing databases and other persistent data requires careful planning.</li></ul><h4>💡 Ways to Deploy with Docker</h4><ul><li><strong>Local Deployment<br></strong>Run containers on your own machine for development and testing.</li><li><strong>Server Deployment (VMs)<br></strong>Run Docker on a Linux server and deploy containers.<br>Example: DigitalOcean droplet, AWS EC2, or dedicated servers.</li><li><strong>Cloud-Native Deployment<br></strong>Use managed container services like AWS ECS, Google Cloud Run, or Azure Container Instances. The cloud handles server management, so you only focus on your containers.</li><li><strong>Orchestration with Kubernetes/ Docker Swarm<br></strong>For large-scale microservices, orchestration platforms provide auto-scaling, load balancing, and self-healing. Kubernetes has become the industry standard.</li></ul><h4>👥 Who Can Access a Docker-Deployed App?</h4><p>Access depends on how you configure it:</p><ul><li><strong>Local only</strong> → The app is accessible only on your machine via localhost.</li><li><strong>Within a network</strong> → Devices on the same LAN or cluster can access.</li><li><strong>Public internet</strong> → Anyone can access it if exposed via a server IP or domain. Usually, this is secured with firewalls, API gateways, or load balancers.</li></ul><h4>🐳Docker Deployment— Locally — Step-by-step Guide</h4><p>This step-by-step guide shows how to <strong>containerize a Spring Boot application with Docker</strong> and <strong>connect it to a MySQL database</strong>. It covers both <strong>single-project setup</strong> and <strong>Maven multi-module project setup</strong>, providing templates and commands to build, run, and manage your containers efficiently. By following this guide, you’ll learn how to create a consistent and portable development environment for your app.</p><h4>01. Prerequisites</h4><ol><li>Docker installed and running (<strong>Docker Desktop </strong>or <strong>Docker Engine</strong>)</li><li>Docker Compose installed (Usually bundled with Docker Desktop)</li><li>A Spring Boot project that builds to an executable jar.</li></ol><h4>02. Project Structure (single-module example)</h4><pre>my-spring-app/<br>├─ pom.xml<br>├─ src/<br>│  └─ main/java/...<br>├─ Dockerfile<br>├─ docker-compose.yml<br>└─ .dockerignore</pre><blockquote><em>📝</em><strong>Note: </strong>Put the Dockerfile at the project root for a single module.</blockquote><h4>03. Containerize a service (create a Dockerfile)</h4><p><strong>🐳What is a Dockerfile?<br></strong>A <strong>Dockerfile</strong> is a text file that contains a set of instructions to build a Docker image. Think of it like a <strong>recipe </strong>where it tells Docker step by step how to package your application (code + dependencies + runtime environment) into a single portable image.</p><p>Create a Dockerfile in your Spring Boot app folder and add below code.</p><pre># ----------------------------<br># Stage 1: Build stage (Maven + JDK)<br># ----------------------------<br>FROM maven:3.9.11-eclipse-temurin-21 AS build<br><br># Set working directory inside container<br>WORKDIR /build<br><br># Copy only the pom.xml first &amp; download dependencies for caching<br>COPY pom.xml .<br>RUN mvn dependency:go-offline -B<br><br># Copy the source code into container<br>COPY src ./src<br><br># Build the jar (skip tests for faster build; remove -DskipTests if needed)<br>RUN mvn clean package -DskipTests<br><br># ----------------------------<br># Stage 2: Runtime stage (smaller image with JRE only)<br># ----------------------------<br>FROM eclipse-temurin:21-jre<br><br># Set working directory for runtime<br>WORKDIR /app<br><br># Copy the built jar from the build stage<br>COPY --from=build /build/target/*.jar app.jar<br><br># Expose the port your app listens on<br># CHANGE this if your app uses a different port<br>EXPOSE 8080<br><br># Start the application<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><ul><li><strong>FROM maven:3.9.11-eclipse-temurin-21 AS build<br></strong>This sets the base image for the <strong>build stage</strong>. It includes Maven 3.9.11 and Eclipse Temurin JDK 21, which are needed to compile Java code and package it into a jar. The tag 3.9.11-eclipse-temurin-21 ensures the image matches the project’s Maven and Java versions. You can browse available tags on <a href="https://hub.docker.com/_/maven">Docker Hub</a> to choose one that fits your setup.</li><li><strong>WORKDIR /build<br></strong>Sets the working directory inside the container to /build. <br>All subsequent commands run from this folder.</li><li><strong>COPY pom.xml . <br></strong>Copies the pom.xml file into the build container.</li><li><strong>RUN mvn dependency:go-offline -B</strong><br>Tells Maven to download all project dependencies in advance. This step is cached in the Docker layer, so rebuilding the image later is faster if dependencies haven’t changed.</li><li><strong>COPY src ./src <br></strong>Copies all Java source files into the build container.</li><li><strong>RUN mvn clean package -DskipTests<br></strong>Compiles the project and packages it into a jar file. The -DskipTests flag skips running tests to speed up example builds.</li><li><strong>FROM eclipse-temurin:21-jre<br></strong>Starts the <strong>runtime stage</strong>. This image is smaller because it only contains the JRE (no Maven), keeping the final image lightweight.</li><li><strong>WORKDIR /app <br></strong>Sets the working directory for runtime image. The jar file will live here.</li><li><strong>COPY --from=build /build/target/*.jar app.jar<br></strong>Copies the jar produced in the build stage into /app/app.jar. Using a wildcard ensures it works with snapshot or versioned jar names.</li><li><strong>EXPOSE 8080<br></strong>Documents that the application listens on port 8080. Note: EXPOSE does <strong>not</strong> publish the port. To access the app from your host machine, use docker run -p 8080:8080 or map ports via Docker Compose.</li><li><strong>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]<br></strong>Starts the Spring Boot application when the container runs.</li></ul><h4>04. dockerignore file (recommended)</h4><p>Create a <strong>.dockerignore</strong> file in your project root to <strong>make builds faster and reduce image size</strong> by excluding unnecessary files:</p><pre>target<br>.git<br>.idea<br>.vscode<br>*.log<br>.DS_Store</pre><h4><strong>05. </strong>docker-compose.yml file (MySQL + Spring Boot App)</h4><p><strong>🐳What is a docker-compose.yml?</strong><br>A <strong>docker-compose.yml</strong> file is a YAML configuration file that defines and runs <strong>multiple Docker containers together</strong> as a single application.</p><p>Instead of starting each container manually, it allows to declare all services in one file and run them up with a single command.</p><p>Place the <strong>docker-compose.yml</strong> file at your project root.</p><p>Example:</p><pre># ------------------------<br># Docker Compose Template<br># ------------------------<br>version: &#39;3.8&#39;<br><br>services:<br>  # MySQL database service<br>  mysql:<br>    image: mysql:8.0                 # Change version if needed<br>    container_name: mysql-dev        # Change container name if needed<br>    environment:<br>      MYSQL_ROOT_PASSWORD: &lt;root_password&gt;  # Replace with your root password<br>      MYSQL_DATABASE: &lt;db_name&gt;             # Replace with your database name<br>      MYSQL_USER: &lt;db_user&gt;                 # Replace with your app DB user<br>      MYSQL_PASSWORD: &lt;db_password&gt;         # Replace with app DB user password<br>    ports:<br>      - &quot;&lt;host_port&gt;:3306&quot;           # Map host port to container port<br>    volumes:<br>      - mysql_data:/var/lib/mysql    # Persist database files<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;mysqladmin&quot;, &quot;ping&quot;, &quot;-u&quot;, &quot;root&quot;, &quot;-p&lt;root_password&gt;&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br>    networks:<br>      - backend<br><br>  # Spring Boot application service<br>  spring-app:<br>    build:<br>      context: .                     # Path to Dockerfile<br>      dockerfile: Dockerfile         # Dockerfile name (if different, change)<br>    container_name: spring-app       # Change container name if needed<br>    depends_on:<br>      mysql:<br>        condition: service_healthy   # Wait until MySQL is healthy<br>    ports:<br>      - &quot;&lt;host_app_port&gt;:8080&quot;       # Map host port to app port<br>    environment:<br>      SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/&lt;db_name&gt;  # Use the internal MySQL port 3306, not the host mapping (3307). Containers communicate via the Docker network, so the host port is irrelevant inside the network.<br>      SPRING_DATASOURCE_USERNAME: &lt;db_user&gt;<br>      SPRING_DATASOURCE_PASSWORD: &lt;db_password&gt;<br>    networks:<br>      - backend<br><br># Networks<br>networks:<br>  backend:<br>    driver: bridge<br><br># Volumes<br>volumes:<br>  mysql_data:</pre><ul><li><strong>version: &quot;3.8&quot;</strong> — Specifies the Compose file format version. Using the latest stable version is recommended.</li><li><strong>services:</strong> — Lists all containers. In the example, we have:<br> 1. mysql — MySQL database.<br> 2. docker-guide — Spring Boot application.</li></ul><p><strong>MySQL database service details (</strong><strong>mysql):</strong></p><ul><li><strong>image:</strong> — Pulls the official MySQL image.</li><li><strong>environment:</strong> — Sets up built-in variables that bootstrap MySQL.</li><li><strong>volumes: </strong>— Persists database files in a named volume.</li><li><strong>ports:</strong> &quot;3307:3306&quot; — Maps host port 3307 to container port 3306 (for connecting from your laptop). Other containers communicate via the Docker network, so this mapping isn’t required internally.</li><li><strong>healthcheck:</strong> — Pings MySQL to ensure readiness.</li><li><strong>networks:</strong> — Connects the container to the backend network so your Spring Boot app can reach it.</li></ul><p><strong>Spring Boot service details:</strong></p><ul><li><strong>build: — </strong>Builds the Docker image from the Dockerfile.</li><li><strong>depends_on: </strong>— Waits until MySQL is healthy before starting.</li><li><strong>ports: — </strong>Maps container port 8080 to the host for access.</li><li><strong>environment: — </strong>Overrides Spring Boot datasource properties to point to the MySQL container.</li></ul><blockquote><em>📝</em><strong>Note: </strong>If you only have <strong>one service</strong> (Ex: only the Spring Boot app without MySQL), you <strong>don’t really need</strong> a <em>docker-compose.yml</em> file. In that case, you can just build and run your container directly with <em>docker run</em>.</blockquote><h4>06. Common Commands to Run</h4><p>All these commands should be run in the <strong>project root directory</strong>, where your Dockerfile and docker-compose.yml are located.</p><p><strong>1. Build Spring Boot Docker image:</strong></p><pre>docker build -t &lt;image-name&gt; .</pre><ul><li>Builds the Spring Boot Docker image from your Dockerfile in the current Directory ( . ).</li><li>Replace &lt;image-name&gt; with a name/tag for your image.</li><li>Use this whenever you <strong>change your Dockerfile or application code</strong> to rebuild the image.</li></ul><blockquote><em>📝</em><strong>Note: </strong>This command <strong>only builds the image</strong>; it does <strong>not start containers</strong>. To run the app, use docker run or docker compose up.</blockquote><p><strong>2. Run a Spring Boot App Separately:</strong></p><pre>docker run -p 8080:8080 &lt;image-name&gt;</pre><ul><li>Replace &lt;image-name&gt; with the actual Docker image you built</li><li>Change 8080:8080 if your app runs on a <strong>different port</strong> or you want to map to a different host port.</li><li>Useful for <strong>quickly testing a single service</strong> without starting other containers.</li></ul><p><strong>3. Using Docker Compose (recommended for multi-container apps)</strong></p><pre># Starts all the services in docker-compose file<br>docker compose up<br><br># Build all images and start containers<br># Forces Docker to rebuild images for your services before starting containers.<br># Useful if you changed your Dockerfile or application code.<br>docker compose up --build<br><br># Stop containers<br># Named volumes are not removed by default<br>docker compose down<br><br># View running containers<br>docker ps<br><br># View logs<br>docker compose logs -f<br><br># 4.6 Rebuild a single service<br>docker compose up --build &lt;service-name&gt;</pre><h4>What changes for a <strong>Maven multi-module</strong> project?</h4><pre>repo-root/<br>├─ pom.xml              # parent (reactor) pom<br>├─ module-a/<br>│  └─ pom.xml<br>|  └─ /src<br>|  └─ Dockerfile<br>├─ module-b/<br>│  └─ pom.xml<br>|  └─ /src<br>|  └─ Dockerfile<br>└─ docker-compose.yml</pre><p><strong>Example Dockerfile for a multi-module project’s module:</strong></p><p><strong>Key Differences:<br></strong>1. The Dockerfile for a module normally lives inside &lt;module-name&gt;/ .<br>2. But in Maven multi-module setup, the parent pom.xml lives outside the module in the project root. So you should copy that too</p><pre># ====== Build Stage ======<br>FROM maven:3.9.11-eclipse-temurin-21 AS build<br>WORKDIR /build<br><br># Copy the root pom.xml (parent) to download dependencies<br>COPY ../pom.xml .<br><br># Copy only the module pom.xml (replace MODULE_NAME with actual module)<br>COPY pom.xml &lt;MODULE_NAME&gt;/pom.xml<br>RUN mvn -N -f &lt;MODULE_NAME&gt;/pom.xml dependency:go-offline -B<br><br># Copy module source<br>COPY &lt;MODULE_NAME&gt; &lt;MODULE_NAME&gt;<br><br># Build the specific module<br>RUN mvn -N -f &lt;MODULE_NAME&gt;/pom.xml clean package -DskipTests<br><br># ====== Runtime Stage ======<br>FROM eclipse-temurin:21-jre<br>WORKDIR /app<br><br># Copy the built jar from the build stage<br>COPY --from=build /build/&lt;MODULE_NAME&gt;/target/&lt;MODULE_NAME&gt;-*.jar &lt;MODULE_NAME&gt;.jar<br><br># Expose the port (replace with actual service port)<br>EXPOSE &lt;PORT&gt;<br><br># Run the application<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;&lt;MODULE_NAME&gt;.jar&quot;]</pre><blockquote><em>📝</em><strong>Note: </strong>If your module depends on another module, you must copy <strong>both the dependent module’s </strong>pom.xml<strong> and </strong>src<strong> folder</strong> along with your own module when building the Docker image. On the safe side, you can simply copy the <strong>entire project</strong> using COPY . . and then build only the desired module and its dependencies with Maven. This will slightly increases Docker build context size.</blockquote><p>In that case, the Dockerfile can be created like this:</p><pre># ===== Build Stage =====<br>FROM maven:3.9.11-eclipse-temurin-21 AS build<br>WORKDIR /build<br><br># Copy the whole project (or just the module + its dependencies)<br>COPY . .<br><br># Build the target module and its dependent modules (replace &lt;MODULE_NAME&gt;)<br>RUN mvn clean package -pl &lt;MODULE_NAME&gt; -am -DskipTests<br><br># ===== Runtime Stage =====<br>FROM eclipse-temurin:21-jre<br>WORKDIR /app<br><br># Copy the built jar from the build stage<br>COPY --from=build /build/&lt;MODULE_NAME&gt;/target/&lt;MODULE_NAME&gt;-*.jar &lt;MODULE_NAME&gt;.jar<br><br># Expose the port (replace with actual service port)<br>EXPOSE &lt;PORT&gt;<br><br># Command to run the application<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;&lt;MODULE_NAME&gt;.jar&quot;]</pre><p><strong>Example </strong><strong>docker-compose.yml file:</strong></p><p><strong>Key Differences:</strong></p><ul><li><strong>context: .</strong> <br>Ensures Docker build has access to parent pom.xml and other modules.</li><li><strong>dockerfile:</strong> points to the module-level Dockerfile.</li></ul><pre>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: &lt;MODULE_NAME&gt;/Dockerfile<br>    ports:<br>      - &quot;8080:8080&quot;<br>    networks:<br>      - backend</pre><h4>🚀 Clone the Sample code:</h4><pre>https://github.com/ThejMal01/docker-beginner-guide.git</pre><h4>🔑 Final Thoughts</h4><p>Docker deployment isn’t just about running apps in containers — it’s about ensuring software is delivered <strong>consistently, quickly, and reliably</strong> across any environment. It bridges the gap between developers and operations, turning deployment from a headache into a smooth, repeatable process.</p><p>Whether you’re just testing locally, deploying to a single VM, or scaling across a Kubernetes cluster, Docker remains a powerful ally in modern software development and deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1642659afa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud Config: Implementing centralized configuration in microservices.]]></title>
            <link>https://medium.com/@thejani.mallawaarachchi/spring-cloud-config-implementing-centralized-configuration-in-microservices-017a75fa8cc9?source=rss-9ddc43bccb4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/017a75fa8cc9</guid>
            <category><![CDATA[access-private-git-repos]]></category>
            <category><![CDATA[config-server-setup]]></category>
            <category><![CDATA[config-client-setup]]></category>
            <category><![CDATA[profile-based-configs]]></category>
            <category><![CDATA[spring-cloud-config]]></category>
            <dc:creator><![CDATA[Thejani Mallawaarachchi]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 07:32:05 GMT</pubDate>
            <atom:updated>2025-08-26T07:32:05.992Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In a microservices architecture, each service often maintains its own configuration in application.properties or application.yml. While this approach may work for small systems, it quickly becomes unmanageable as the number of services and environments (development, testing, staging, production) grows. Developers must update configurations across multiple repositories, which is both error-prone and time-consuming. Storing sensitive data such as database credentials or API keys within each service’s codebase further increases security risks.</p><p><strong>Spring Cloud Config</strong> addresses these challenges by providing a <strong>centralized configuration management solution</strong>. It allows all configurations to be stored in a single external repository and distributed to microservices through a client-server architecture. The <strong>Config Server</strong> reads configuration data from the repository and exposes it via REST endpoints, while <strong>Config Clients</strong> (the microservices) fetch and apply these configurations dynamically. This approach ensures consistency, security, and simplified management of application settings across multiple environments.</p><h4><strong>Architecture Overview</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnYIKZ4Ie1RTE6MaHF0U_A.png" /><figcaption>Spring Cloud Config Architecture Overview</figcaption></figure><ol><li><strong>Spring Cloud Config Server</strong> connects to a configuration source (mostly a Git repository, but it can also use file systems, Vault, JDBC, etc.).</li><li>Config Server serves <strong>environment-specific properties</strong> based on service name and profile.</li><li>Each <strong>microservice client</strong> fetches its configuration from the Config Server at startup (and optionally on refresh).</li></ol><p>In this article, we utilize a Git repository as the configuration source.</p><h3>Spring Cloud Config Server Setup</h3><h4><strong>Step 01: Prepare Config Repository</strong></h4><p>Create a Git repo and add some sample configuration files. <br>(config-client-dev.properties, config-client-prod.properties, etc.)</p><h4><strong>Step 02: Create a Spring Boot Project for the Config Server</strong></h4><p><strong>01. Create a new project<br></strong>Use Spring Initializr or your preferred IDE to create a <strong>Maven Spring Boot project</strong> for the Config Server. Choose a stable Spring Boot version and add the <strong>Spring Cloud Config Server </strong>dependency.</p><p>For this guide, we use <strong>Java 21</strong>, <strong>Spring Boot 3.5.5</strong>, and <strong>Spring Cloud 2025.0.0</strong> to ensure compatibility.</p><p><strong>02. Add the Config Server dependency</strong><br>If you didn’t add the Config Server dependency while creating the project, include the following in your pom.xml file under dependencies.</p><pre>&lt;dependency&gt;<br>     &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>     &lt;artifactId&gt;spring-cloud-config-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><a href="https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-config-server">Spring Cloud Config Server</a></p><blockquote><em>📝</em><strong>Note:</strong> Specifying a version is optional. If your project uses Spring Boot’s managed dependencies or a BOM, Maven usually selects a compatible version automatically.</blockquote><h4><strong>Step 03: Enable Config Server</strong></h4><p>In the main application class (ConfigServerApplication.java), add the @EnableConfigServer annotation. Without this annotation, the application will run as a standard Spring Boot application, and it won’t expose the endpoints necessary to serve configuration files to client applications.</p><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.config.server.EnableConfigServer;<br><br>@SpringBootApplication<br>@EnableConfigServer<br>public class ConfigServerApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(ConfigServerApplication.class, args);<br>    }<br><br>}</pre><h4><strong>Step 04: Configuring the Config Server</strong></h4><p>A Spring Cloud Config Server must be properly configured in its application.yml file to access the Git repository that stores the configuration properties of the client applications. This configuration specifies the repository location and, for private repositories, the required authentication credentials. Without it, the server cannot locate or serve the configuration files. The Config Server supports multiple authentication methods, depending on whether the repository is public or private.</p><p><strong>01. Public Repository (No Authentication)<br></strong>If your Git repository is public, the Config Server can fetch configuration properties directly without requiring any credentials.</p><pre>spring:<br>  application:<br>    name: config-server<br>  cloud:<br>    config:<br>      server:<br>        git:<br>          uri: https://github.com/&lt;your-org&gt;/&lt;repo-name&gt;.git # config repository url<br>          default-label: main # branch to fetch<br>          clone-on-start: true<br>server:<br>  port: 8888</pre><blockquote><strong>⚠️ Note:</strong> Even though public repos work without authentication, sensitive information should <strong>never</strong> be stored in them.</blockquote><p><strong>02. HTTP(S) Access with Username and Password<br></strong>For private repositories, you can provide your GitHub <strong>username and password </strong>along with the repository URI in the Config Server configuration. However, this approach is not recommended as it exposes credentials in plain text and poses security concerns.</p><p><strong>03. HTTP(S) Access with Personal Access Token<br></strong>More secure than the username/password approach. Use a <strong>GitHub Personal Access Token</strong> (PAT) instead of a password.</p><p><strong>🔑 Steps to Generate a GitHub PAT<br></strong>Refer to <a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token">Creating a fine-grained personal access token</a> to create a PAT.</p><blockquote>⚠️ <strong>Note</strong>: Use a <strong>fine-grained token</strong> instead of a <strong>classic token</strong> because it allows repository-specific and permission-specific access, following the principle of <strong>least privilege</strong>. Classic tokens are broader and less secure, as they could expose all your repositories if leaked.</blockquote><p><strong>Resource owner </strong>— Select your GitHub account or organization<br><strong>Repository access — </strong>Choose <strong>Only select repositories</strong> and pick config repo.<br><strong>Permissions — </strong>Add <strong>Contents </strong>permission <strong>Read-only </strong>(Minimal permissions)</p><p>Now use the copied Personal Access Token (PAT) in your Spring Cloud Config Server application.yml:</p><pre>spring:<br>  application:<br>    name: config-server<br>  cloud:<br>    config:<br>      server:<br>        git:<br>          uri: https://github.com/&lt;your-org&gt;/&lt;repo-name&gt;.git # config repository uri<br>          default-label: main # branch to fetch<br>          username: &lt;your-github-username&gt;<br>          password: &lt;your-fine-grained-token&gt;          <br>          clone-on-start: true<br>server:<br>  port: 8888</pre><blockquote><strong>⚠️ Note:</strong> Replace &lt;your-github-username&gt; and &lt;your-personal-access-token&gt; with your actual GitHub username and the PAT you just generated.</blockquote><p><strong>04. SSH Key Authentication<br></strong>For secure and passwordless access to private Git repositories, Spring Cloud Config Server can authenticate using SSH keys. This method is safer than using passwords or tokens and is ideal for automated deployments.</p><p><strong>🔑 Steps for SSH Key Authentication</strong><br><strong>1. Generate an SSH Key Pair</strong><br>By default, Spring Cloud Config Server uses JGit to access Git repositories, and JGit requires RSA keys in PEM format.</p><p>Refer to <a href="http://JGit requires RSA keys in PEM format. Below is an example ssh-keygen (from openssh) command that will generate a key in the corect format:">Spring Cloud Config docs</a> for more details on SSH key usage, or run the following command to generate a 4096-bit RSA SSH key:</p><pre>ssh-keygen -m PEM -t rsa -b 4096 -C &quot;your-email@example.com&quot;</pre><p>Press Enter to save it in the default location, or provide a custom path.<br>Optionally, set a passphrase for extra security.</p><p><strong>2. Add Public SSH Key to GitHub<br></strong>Copy the contents of your public key file (.ssh.pub/ id_rsa.pub).<br>Go to <strong>GitHub → Settings → SSH and GPG keys → </strong>click <strong>New SSH Key</strong><br>Provide a title, paste the public key content, and save.</p><blockquote><em>📝</em><strong>Note: </strong>You can test the connection using the following command.</blockquote><pre>ssh -i /path/to/private_key -T git@github.com</pre><p><strong>3. Configure the Config Server to use the private key<br></strong>Use SSH URI instead of HTTPS.<br>Make sure the <strong>private key in </strong>.yml matches the public key in GitHub.</p><pre>spring:<br>  application:<br>    name: config-server<br>  cloud:<br>    config:<br>      server:<br>        git:<br>          uri: git@github.com:&lt;your-org&gt;/&lt;repo-name&gt;.git # SSH config repository uri<br>          default-label: main # branch to fetch<br>          private-key: |<br>            -----BEGIN RSA PRIVATE KEY-----<br>            more-lines-here<br>            -----END RSA PRIVATE KEY-----<br>          passphrase: &lt;passphrase-of-ssh-key&gt; # use only if you set a passphrase<br>          ignore-local-ssh-settings: true<br>          clone-on-start: true<br>server:<br>  port: 8888</pre><blockquote><strong>⚠️ Note: Careful with Indentation</strong><br>When adding an SSH private key to application.yml using the | literal block, all lines of the key must be indented exactly one level under the key.</blockquote><blockquote><strong>Note: </strong>You can verify the config server and repository connection by accessing the following URL in a browser or using a tool like Postman:</blockquote><pre>http://localhost:8888/&lt;application-name&gt;/&lt;profile&gt;</pre><blockquote><strong>Example: </strong>For config file config-client-dev.yml (&lt;app-name&gt;-&lt;profile&gt;.yml), the URL would be:</blockquote><pre>http://localhost:8888/config-client/dev</pre><blockquote>This will return a JSON response containing the configuration properties for the specified application and profile.</blockquote><h4>Spring Cloud Config Client Setup</h4><p>Once the Config Server is set up, the next step is to configure your microservices as <strong>Config Clients</strong>, enabling them to fetch configuration properties from the centralized repository.</p><h4><strong>Step 01: Create a Spring Boot Project </strong>for the Config Client</h4><p>Create a Spring Boot project and add the following dependencies.</p><pre>&lt;!-- Spring Cloud Config Client --&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;!-- Optional --&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Step 02: Configure the Config Client</strong></h4><p>Create an application.yml in the client project and add the following configuration:</p><pre>spring:<br>  application:<br>    name: config-client                          # Name of this microservice<br>  config:<br>    import: &quot;configserver:http://localhost:8888&quot; # URL of the Config Server<br>  profiles:<br>    active: dev                                  # Active profile (dev, test, prod, etc.)<br>  cloud:<br>    config:<br>      enabled: true                              # Enable Spring Cloud Config<br>      fail-fast: true                            # Fail if the Config Server is unreachable<br>      retry:<br>        max-attempts: 3                          # Retry fetching configuration up to 3 times</pre><blockquote><em>📝 </em><strong>Note: </strong>The spring.application.name must match the config file name, and spring.profiles.active must match the profile suffix in the Config Server repo (&lt;app-name&gt;-&lt;profile&gt;.yml). Also, ensure the Config Server is running and accessible at the configured URL (<em>http://localhost:8888</em>).</blockquote><h4><strong>Step 03: Manage Profiles</strong></h4><p>Profiles allow you to maintain <strong>environment-specific configurations</strong> (like dev, test, prod etc.) for each microservice.</p><p><strong>01. Flat Structure (All files in root)</strong></p><p>In a single-repo flat structure, the Config Server looks for files like:</p><pre>config-repo/<br>├─ config-client.yml           # Default configuration for all environments<br>├─ config-client-dev.yml       # For dev profile<br>├─ config-client-test.yml      # For test profile<br>├─ config-client-prod.yml      # For production</pre><p>File Naming Format: &lt;application-name&gt;-&lt;profile&gt;.yml or .properties</p><p>Client Configuration Example:</p><pre>spring:<br>  application:<br>    name: config-client<br>  profiles:<br>    active: dev</pre><blockquote><em>📝</em><strong>Note: </strong>When the client starts, it fetches <strong>default file </strong>(<strong>config-client.yml</strong>) and <strong>active profile file </strong>(<strong><em>config-client-dev.yml</em></strong>)<strong> </strong>configuration from Config Server.</blockquote><p><strong>02. Folder per Service Structure (using </strong><strong>search-paths)</strong></p><p>For multiple services in a single repository:</p><pre>config-repo/<br> ├── service-a/<br> │    ├── service-a.yml<br> │    ├── service-a-dev.yml<br> ├── service-b/<br> │    ├── service-b.yml<br> │    ├── service-b-prod.yml</pre><p>Config Server application.yml example:</p><pre>spring:<br>  cloud:<br>    config:<br>      server:<br>        git:<br>          uri: https://github.com/&lt;your-org&gt;/&lt;repo-name&gt;<br>          search-paths: service-a, service-b</pre><p>Example URL to fetch configuration for service-a dev profile:</p><pre>http://localhost:8888/service-a/dev</pre><p>This fetches both the default (service-a.yml) and the active profile file (service-a-dev.yml) for service-a.</p><blockquote><strong>⚠️ Note:</strong> If multiple files with the same application name and profile exist (e.g., one at the root and one in a subfolder or in subfolders), Spring Cloud Config merges them by default.</blockquote><p><strong>03. Mixed Folder Structure with </strong><strong>application.yml Naming</strong></p><p>You can use conventional application.yml naming inside service folders:</p><pre>config-repo/<br> ├── service-a/<br> │    ├── application.yml       # Default for service-a<br> │    ├── application-dev.yml   # Dev profile for service-a<br> ├── service-b/<br> │    ├── application.yml       # Default for service-b<br> │    ├── application-prod.yml  # Prod profile for service-b</pre><p>Client Configuration:</p><pre>spring:<br>  application:<br>    name: service-a<br>  profiles:<br>    active: dev</pre><p>Access URL:</p><pre>http://localhost:8888/service-a/dev</pre><p>This loads application.yml + application-dev.yml from service-a folder.</p><p><strong>04. Multi-Repository Setup</strong></p><p>Instead of a single repository, the Config Server can point to multiple repositories.</p><p><strong>Note: </strong>Refer to the <a href="https://docs.spring.io/spring-cloud-config/docs/current/reference/html/#_pattern_matching_and_multiple_repositories">Spring Cloud Config documentation</a> for advanced multi-repo and pattern-based setups.</p><h4>Access Configuration Properties in the Client</h4><p>Once the Config Client is set up, it should automatically fetch its configurations from the Config Server based on:<br>spring.application.name → matches the application name in the repo (config-client)<br>spring.profiles.active → loads the relevant profile (dev, test, prod)</p><p>For example, suppose your config-client-dev.ymlcontains:</p><pre>welcome-message:<br>  Hello from Config Server!<br>server:<br>  port: 8081</pre><p>The client will start on port 8081<strong> </strong>as defined in the repo.</p><p>Additionally, you can inject and use properties in your Spring Boot application like this:</p><pre>@RestController<br>public class WelcomeController {<br><br>    @Value(&quot;${welcome-message}&quot;)<br>    private String welcomeMessage;<br><br>    @GetMapping(&quot;/welcome&quot;)<br>    public String getWelcomeMessage() {<br>        return welcomeMessage;<br>    }<br>}</pre><p>Access in browser or Postman:</p><pre>http://localhost:8081/welcome</pre><p>You should see the value returned from the Config Server:</p><pre>Hello from Config Server!</pre><h4><strong><em>🚀 Clone the Sample code:</em></strong></h4><pre>https://github.com/ThejMal01/spring-cloud-config-server-setup.git</pre><h4>Key <strong>benefits of Spring Cloud Config:</strong></h4><ul><li><strong>Single Source of Truth<br></strong>All configs are stored in one place (typically a Git repo).</li><li><strong>Environment Segregation<br></strong>Separate configs for dev, test, and prod are managed easily.</li><li><strong>Dynamic Refresh<br></strong>With Spring Cloud Bus, services can reload configs without a restart.</li><li><strong>Security<br></strong>Secrets can be stored securely in one place and accessed centrally.</li></ul><h4>Drawbacks of Spring Cloud Config:</h4><ul><li><strong>Single Point of Failure (SPOF)<br></strong>If the Config Server is down and fail-fast is enabled, client apps may fail to start. Needs a high-availability setup.</li><li><strong>Startup Dependency<br></strong>Config clients depend on the Config Server being available <strong>before startup</strong>, unless you disable fail-fast.</li><li><strong>Latency / Performance Overhead<br></strong>Fetching config from a remote server can add latency. Needs proper caching or refresh strategies to avoid unnecessary calls.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=017a75fa8cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>