Home > database >  Dockerized Spring Boot App Ignoring K8s/Kubernetes Environment Variables
Dockerized Spring Boot App Ignoring K8s/Kubernetes Environment Variables

Time:06-20

I have a very simple containerized Spring Boot application that I am trying to deploy to Docker Desktop Kubernetes.

My application.yaml looks like:

spring:
  application:
    name: helloworld
  datasource:
    password: ${SPRING_DATASOURCE_PASSWORD:secretpassword}
    url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/helloworld}
    username: ${SPRING_DATASOURCE_USERNAME:helloworld}

My Dockerfile looks like:

FROM openjdk:17 AS build
WORKDIR /workspace/app
COPY ../mvnw .
COPY ../.mvn .mvn
COPY ../pom.xml .
COPY ../src src
RUN ./mvnw install -DskipTests


FROM openjdk:17
VOLUME /tmp
COPY --from=build /workspace/app/target/*.jar app.jar
ENTRYPOINT ["java", "-jar","/app.jar"]

My deployment.yml looks like:

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: helloworld
  name: helloworld
spec:
  replicas: 1
  selector:
    matchLabels:
      app: helloworld
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: helloworld
    spec:
      containers:
      - image: xxx/yyy
        name: zzz
        resources: {}
        env:
        - name: SPRING_DATASOURCE_URL
          value: "jdbc:postgresql:host.docker.internal:5432/helloworld"
status: {}

When I run kubectl get all I can see the pod is in a "CrashLoopBackoff"

When I run (before the pod crashes)

kubectl exec POD_NAME -- printenv

I can see the environment variable has been created (or I get an error I assume is because of the pod crashing: error: unable to upgrade connection: container not found ("yyy"))

But when I check the logs, I see:

SQL State  : 08001
Error Code : 0
Message    : Connection to localhost:5432 refused.

So the Spring Boot app is not picking up the environment variable SPRING_DATASOURCE_URL. It is still trying to connect to localhost:5432

If I add the env variable to the docker-compose (or IntelliJ runtime config) and run outside of K8s, the Spring Boot application picks up the environment variable.

Any idea what I am doing wrong?

CodePudding user response:

The value of the env variable was causing the issue. It should be:

env:
  - name: SPRING_DATASOURCE_URL
    value: jdbc:postgresql://host.docker.internal:5432/helloworld

Because I was missing the // it kept referring trying to connect to localhost. Which was very confusing.

  • Related