要傳入變數(如db server address、redis address、port等進container在docker-compose和kubernetes裡有點類似,
假如我們要傳任意字串、數字或是address進nestjsapi pod,
新增env在nestjsapi-deployment.yaml下spec/template/spec/containers下
template:
metadata:
labels:
component: api
spec:
containers:
- name: nestjsapi
image: yirengoo/nestjsapi:v4
ports:
- containerPort: 5000
env:
- name: ANYTHING # key
value: test # value
- name: ANYNUMBER
value: '99' # 數字要轉字串
- name: PG_HOST
# 指定service name連到postgres
value: postgres-clusterip-service
如果是密碼或是第三方api key想要加密的話,可以使用Kubernetes Secret
kubectl create secret secret_type secret_name --from-literal key=value
secret type有兩種
以建立PG_PASSWORD為例
kubectl create secret generic pgpw --from-literal password=root
作為環境變數傳入nestjsapi pod
template:
metadata:
labels:
component: api
spec:
containers:
- name: nestjsapi
image: yirengoo/nestjsapi:v4
ports:
- containerPort: 5000
env:
- name: ANYTHING
value: test
- name: ANYNUMBER
value: '99'
- name: PG_HOST
value: postgres-clusterip-service
- name: PG_PASSWORD
valueFrom:
secretKeyRef: # 指定secret ref
name: pgpw # kubectl命令中的secret name*
key: password # kubectl命令中的key
在postgre deployment下的postgres pod的docker image預設是沒有密碼的
postgres official docker image說明可知道PGPASSWORD是設定初始密碼
新增PGPASSWORD環境變數
# postgres-deployment.yaml
...
template:
metadata:
labels:
component: pgdb
spec:
volumes:
- name: pgdb-storage
persistentVolumeClaim:
claimName: postgres-pvc
containers:
- name: postgres
image: postgres
ports:
- containerPort: 5432
volumeMounts:
- name: pgdb-storage
mountPath: /var/lib/postgressql/data
subPath: postgres
env:
- name: PGPASSWORD # 設定postgres superuser密碼
valueFrom: # 跟在api端的設定一
secretKeyRef:
name: pgpw
key: password
這樣設定有個好處,即便部署到Google Cloud或是AWS,仍需要在terminal下建立secret,密碼比較相對安全