从Kubernetes中部署的应用程序连接到外部数据库

问题描述:

我正在minikube中部署一个Spring Boot应用程序,该应用程序连接到主机上运行的数据库.按照12个因素的应用程序建议,我使用环境变量进行必要的配置:

I'm deploying a Spring Boot app in minikube that connects to a database running on the host. Following the 12 factor app recommendations I use environment variables for the necessary configuration:

SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver
SPRING_DATASOURCE_PASSWORD=...
SPRING_DATASOURCE_URL=jdbc:postgresql://<HOST_IP_FROM_K8S>:5432/myservice
SPRING_DATASOURCE_USERNAME=...

kubernetes文档仅显示了如何在我不想做的服务和部署.yaml文件中设置环境变量.创建部署时,是否可以在命令行上为minikube或kubectl传递环境变量? (在Docker中,我使用-e执行此操作.)

The kubernetes docs only show how to set environment variables in the service and deployment .yaml files which I don't want to do. Is there a way to pass environment variables on the command line for minikube or kubectl when I create the deployment? (In Docker I do this with -e.)

请注意,必须在启动应用程序或应用程序崩溃之前设置环境变量.

Note that the environment variables have to be set before starting the app or it crashes.

在上面Ansil的注释之后,我使用了configmapsecret来传递如下配置:

Following Ansil's comment above I used configmap and secret to pass the configuration like this:

kubectl create secret generic springdatasourcepassword --from-literal=SPRING_DATASOURCE_PASSWORD=postgres
kubectl create secret generic springdatasourceusername --from-literal=SPRING_DATASOURCE_USERNAME=postgres
kubectl create configmap springdatasourcedriverclassname --from-literal=SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver
kubectl create configmap springdatasourceurl --from-literal=SPRING_DATASOURCE_URL=jdbc:postgresql://172.18.0.1:5432/bookservice

在以下的deployment.yaml文件中引用了这些文件:

These are referenced in the deployment.yaml file like this:

env:
- name: GET_HOSTS_FROM
  value: dns
- name: SPRING_DATASOURCE_DRIVER_CLASS_NAME
  valueFrom:
    configMapKeyRef:
      name: springdatasourcedriverclassname
      key: SPRING_DATASOURCE_DRIVER_CLASS_NAME
- name: SPRING_DATASOURCE_URL
  valueFrom:
    configMapKeyRef:
      name: springdatasourceurl
      key: SPRING_DATASOURCE_URL
- name: SPRING_DATASOURCE_PASSWORD
  valueFrom:
    secretKeyRef:
      name: springdatasourcepassword
      key: SPRING_DATASOURCE_PASSWORD
- name: SPRING_DATASOURCE_USERNAME
  valueFrom:
    secretKeyRef:
      name: springdatasourceusername
      key: SPRING_DATASOURCE_USERNAME

可以在此处找到完整的说明.

A full explanation can be found here.