skip to Main Content

In my Kubernetes cluster, I have a ConfigMap object containing the address of my Postgres pod. It was created with the following YAML:

apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-configmap
data:
  database_url: postgres-service

Now I reference this value in one of my Deployment’s configuration:

env:
 - name: DB_ADDRESS
   valueFrom:
     configMapKeyRef:
       name: postgres-configmap
       key: database_url

This deployment is a Spring Boot application that intends to communicate with the database. Thus it reads the database’s URL from the DB_ADDRESS environment variable. (ignore the default values, those are used only during development)

datasource:
    url: ${DB_ADDRESS:jdbc:postgresql://localhost:5432/users}
    username:  ${POSTGRES_USER:postgres}
    password:  ${POSTGRES_PASSWORD:mysecretpassword}

So, according to the logs, the problem is that the address has to have the jdbc:postgresql:// prefix. Either in the ConfigMap’s YAML or in the application.yml I would need to concatenate the prefix protocol string with the variable. Any idea how to do it in yml or suggestion of some other workaround?

2

Answers


  1. If you create a Service, that will provide you with a hostname (the name of the service) that you can then use in the ConfigMap. E.g., if you create a service named postgres, then your ConfigMap would look like:

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: postgres-configmap
    data:
      database_url: jdbc:postgresql://postgres:5432/users
    
    Login or Signup to reply.
  2. Kubernetes environment variable declarations can embed the values of other environment variables. This is the only string manipulation that Kubernetes supports, and it pretty much only works in env: blocks.

    For this setup, once you’ve retrieved the database hostname from the ConfigMap, you can then embed it into a more complete SPRING_DATASOURCE_URL environment variable:

    env:
     - name: DB_ADDRESS
       valueFrom:
         configMapKeyRef:
           name: postgres-configmap
           key: database_url
     - name: SPRING_DATASOURCE_URL
       value: 'jdbc:postgresql://$(DB_ADDRESS):5432/users'
    

    You might similarly parameterize the port (though it will almost always be the standard port 5432) and database name. Avoid putting these settings in a Spring profile YAML file, where you’ll have to rebuild your application if any of the deploy-time settings change.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search