问题
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=...
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.
回答1:
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
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.
回答2:
We have no direct option with create
subcommand in kubectl
to pass the environmental variables.
You may use Helm to customize deployment.
(Example: https://docs.bitnami.com/kubernetes/how-to/deploy-java-application-kubernetes-helm/)
来源:https://stackoverflow.com/questions/55667314/connecting-to-an-external-database-from-an-app-deployed-in-kubernetes