skip to Main Content

I’m trying to set some environment variables in k8s deployment and use them within the application.properties in my spring boot application, but it looks like I’m doing something wrong because spring is not reading those variables, although when checking the env vars on the pod, all the vars are set correctly.

The error log from the container:

org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port...

Any help will be appreciated.

application.properties:

spring.datasource.url=jdbc:postgresql://${DB_URL}:${DB_PORT}/${DB_NAME}
spring.datasource.username=${DB_USER_NAME}
spring.datasource.password=${DB_PASSWORD}

DockerFile

FROM openjdk:11-jre-slim-buster
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-deployment
  labels:
    app: api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: .../api
          resources:
            requests:
              memory: "64Mi"
              cpu: "250m"
            limits:
              memory: "128Mi"
              cpu: "500m"
          ports:
            - containerPort: 80
          env:
          - name: DB_URL
            value: "posgres"
          - name: DB_NAME
            valueFrom:
              configMapKeyRef:
                name: postgres-config
                key: dbName
          - name: DB_USER_NAME
            valueFrom:
                secretKeyRef:
                  name: db-secret
                  key: dbUserName
          - name: DB_PASSWORD
            valueFrom:
                secretKeyRef:
                  name: db-secret
                  key: dbPassword

2

Answers


  1. Chosen as BEST ANSWER

    The DockerFile was wrong. Everything is working fine after changing the DockerFile to this:

    FROM maven:3.6.3-openjdk-11-slim as builder
    
    WORKDIR /app
    COPY pom.xml .
    
    COPY src/ /app/src/
    RUN mvn install -DskipTests=true
    
    FROM adoptopenjdk/openjdk11:jre-11.0.8_10-alpine
    
    COPY --from=builder /app/target/*.jar /app.jar
    
    ENTRYPOINT ["java", "-jar", "/app.jar"]
    

  2. You miss the env: in your deployment.yaml, see here : https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/

    if you have kubectl installed you can check how env vars must be declared by doing an explain like follow : kubectl explain deployment.spec.template.spec.containers

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