Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 59

Configuring Docker Images with `docker-compose.yml` Environment Variables

This lesson is built with resources from youtube.com and medium.com.

Hello! Welcome back to our course on building a production-grade blog platform.

In our last lesson, we successfully configured our API Gateway to route requests to the correct downstream microservices. However, we achieved this by hardcoding routing rules directly into the application-docker.properties file, which is packaged inside the gateway's Docker image.

This approach presents a significant problem: our configuration is tightly coupled to our application artifact. If we need to change a database password, a service URL, or a Kafka broker address, we would have to:

  1. Change the code/properties file.
  2. Rebuild the Docker image.
  3. Redeploy the container.

This process is slow, error-prone, and violates a fundamental principle of modern cloud-native development. Today's lesson is about fixing this. We will learn how to externalize configuration, separating it from our application image by using environment variables in our docker-compose.yml file.

MERN Stack Comparison

This concept is standard practice in the MERN world. You are likely familiar with using .env files to store your DATABASE_URL, JWT_SECRET, or API_KEY. Libraries like dotenv load these values into the Node.js environment, making them accessible via process.env.DATABASE_URL. We are going to implement the exact same pattern, but for our Spring Boot services orchestrated by Docker Compose.



1. The "Why": Storing Config in the Environment

Before we dive into the "how," it's crucial to understand the "why." The practice of separating configuration from code is a core tenant of the Twelve-Factor App methodology, a set of best practices for building modern, scalable applications.

I've found an excellent article that breaks this down perfectly. It explains not just the core principle but also provides a clear mental model for classifying different types of configuration and deciding where each should live.

99% of Spring Boot Developers Get Configuration Wrong. Are You ...

The article 'The Ultimate Guide to Spring Boot Microservices Configuration' is a definitive resource on this topic. It introduces the 12-Factor App principle and provides a practical framework for managing configuration in a microservices architecture.

Please read the following sections: 'The Foundation: Understanding the 12-Factor App': Focus on the core rule: "Store config in the environment." 'The 4 Types of Configuration (And Where Each Goes)': Pay close attention to the distinction between Infrastructure Configuration and Application Behavior. 'The Golden Rules (Memorize These)': This is a great summary. Rule #2 and Rule #5 are especially relevant for today's lesson.

Key Takeaways from the article:

  • Code vs. Config: Your compiled application (the JAR file) should be immutable and deployable to any environment. The configuration is what adapts the application to a specific environment (dev, staging, production) or deployment (local Docker, AWS, Kubernetes).
  • Infrastructure & Secrets go in Environment Variables:
    • Secrets: Database passwords, API keys.
    • Infrastructure Config: Database hosts, service URLs, ports.
      These change based on where you deploy, so they must be external.
  • Application Behavior goes in YAML/Properties files: Settings like connection pool size, logging levels, or ddl-auto can be version-controlled and vary by environment profile (e.g., application-dev.yml vs. application-prod.yml).

This separation allows us to build a single Docker image and promote it through different environments, providing different environment variables at runtime.



2. The "How": Docker Compose and Spring Boot

Now that we understand the principle, let's look at the mechanics. This involves two parts: defining the variables in Docker Compose and ensuring Spring Boot can read them.

Part A: Defining Environment Variables in Docker Compose

The simplest way to pass environment variables to a container is using the environment key in your docker-compose.yml. For sensitive data like passwords, the best practice is to store them in a .env file (which you must not commit to Git) and reference them from Docker Compose.

This video provides a clear, practical demonstration of this workflow.

Environment Variables in Docker Compose: Secure Your Secrets!

The video 'Environment Variables in Docker Compose: Secure Your Secrets!' explains the risks of hardcoding secrets and demonstrates the proper way to use a .env file with Docker Compose.

Please watch the following segments: 00:31 - 02:17: Understand the security risks of hardcoding configuration. 05:06 - 06:15: See how to create a .env file and reference its variables in docker-compose.yml using the ${VAR_NAME} syntax. 06:28 - 07:56: This part is critical. It shows why you must add the .env file to your .gitignore.

The flow looks like this:

Setting Environment Variables in Docker Compose
This diagram shows how variables from both the `.env` file and the `docker-compose.yml` file are passed into a running Docker container, effectively externalizing the configuration.

Part B: How Spring Boot Reads Environment Variables

You might be wondering: "If I set an environment variable like SPRING_DATASOURCE_URL in docker-compose.yml, how does Spring Boot know to use it for the spring.datasource.url property?"

The answer is relaxed binding. Spring Boot is smart enough to automatically map environment variable conventions (uppercase, underscore-separated) to its internal property format (lowercase, dot-separated).

This article provides the final piece of the puzzle.

How Spring Boot Maps Environment Variables to Configuration ...

This article, 'How Spring Boot Maps Environment Variables...', explains the 'magic' behind relaxed binding and the configuration priority.

Please read these two key sections: 'Environment Variable Mapping and Normalization': This explains how SPRING_DATASOURCE_URL becomes spring.datasource.url. 'How Spring Resolves Conflicts Between Sources': This covers the priority order. Note that environment variables override values in your application.properties file.

Because of this automatic mapping and high priority, we can simply remove the infrastructure-related properties from our .properties files and define them as environment variables in docker-compose.yml. Spring Boot will pick them up seamlessly.



3. Your Task: Externalize Database and Kafka Configuration (20 minutes)

It's time to apply these concepts to our project. We will move the database and Kafka connection details out of our application-docker.properties files and into docker-compose.yml.

  1. Create a .env File (and ignore it)

    • In the root of your project (microservices-new), create a new file named .env.
    • Add the database credentials to this file. These are the same credentials the postgres service uses.
      POSTGRES_USER=admin
      POSTGRES_PASSWORD=password
      
    • Open your .gitignore file and add .env to it on a new line. This is a critical step to prevent committing secrets.
  2. Update application-docker.properties Files

    • Go to auth-service/src/main/resources/application-docker.properties.
    • Delete the following lines. We will provide these via environment variables instead.
      
      
      
      # DELETE THESE LINES
      spring.datasource.url=jdbc:postgresql://postgres:5432/blog_db
      spring.datasource.username=admin
      spring.datasource.password=password
      spring.kafka.bootstrap-servers=broker:9092
      
    • Repeat the same process for blog-service/src/main/resources/application-docker.properties.
  3. Update docker-compose.yml

    • Open your root docker-compose.yml file.
    • Find the auth-service definition and add an environment section to it.
      services:
        auth-service:
      
      
      
          # ... existing build, ports, depends_on ...
          environment:
            - SPRING_PROFILES_ACTIVE=docker
            - SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/blog_db
            - SPRING_DATASOURCE_USERNAME=${POSTGRES_USER}
            - SPRING_DATASOURCE_PASSWORD=${POSTGRES_PASSWORD}
            - SPRING_KAFKA_BOOTSTRAP_SERVERS=broker:9092
      
      Notice how we are using ${POSTGRES_PASSWORD} to pull the value directly from our new .env file.
    • Copy this same environment block to the blog-service definition.

Your configuration is now successfully externalized! The application images no longer contain any infrastructure-specific details.



4. Runtime Observation & Debugging (15 minutes)

Let's verify that everything still works and practice a debugging scenario.

  1. Rebuild and Relaunch:
    Since we changed the application-docker.properties files (by deleting lines), we need to rebuild the images to ensure those changes are picked up. The --build flag tells Docker Compose to do this.

    
    
    
    # From your project root
    docker-compose up -d --build
    
  2. Inspect the Logs:
    Check the logs for auth-service to confirm it started correctly and connected to the database.

    docker-compose logs -f auth-service
    

    You should see the familiar Spring Boot startup banner and log lines indicating a successful connection to PostgreSQL via HikariCP, without any errors.

  3. Debugging Task: The Misspelled Variable
    This is a very common source of bugs. Let's simulate it.

    • In your docker-compose.yml, go to the auth-service environment variables and introduce a typo. Change SPRING_DATASOURCE_URL to SPRING_DATASORCE_URL.
    • Restart just the auth-service to apply the change:
      docker-compose up -d --no-deps auth-service
      
    • Now, tail the logs again: docker-compose logs -f auth-service.
    • What do you see? The application will fail to start. You will see a long stack trace, but near the top, you should find a clear error message like Failed to configure a DataSource: 'url' attribute is not specified or Description: Failed to determine a suitable driver class.

    This exercise demonstrates that when the application crashes on startup, the first place to check is the configuration it's receiving from its environment. Fix the typo and restart the service to confirm it works again.



Conclusion

Fantastic work today! You have taken a massive step toward building a truly professional-grade application. By externalizing configuration, you have decoupled your application code from its deployment environment, making it more secure, flexible, and maintainable.

Key Takeaways:

  • Following the 12-Factor App methodology, configuration (especially secrets and infrastructure details) must be stored in the environment, not in version-controlled code.
  • You can use an environment block in docker-compose.yml to pass variables to your services.
  • For sensitive data, use a .env file (added to .gitignore) and reference variables with the ${VAR_NAME} syntax.
  • Spring Boot's relaxed binding automatically maps environment variables like SPRING_DATASOURCE_URL to internal properties like spring.datasource.url.
  • Environment variables have a higher priority than .properties files, making them the perfect tool for overriding configuration at runtime.

Preview of the Next Lesson:
We've observed our application's behavior by inspecting its logs. But what if we need to look inside the container? In the next lesson, we will learn how to debug a running container by executing a shell within it, allowing us to inspect its environment variables, file system, and network status directly.