我想连接到一个Postgres实例,它是在一个pod在GKE。
我认为kubectl端口转发是实现这个目标的一种方法。
在我的本地,我有"Docker for desktop";当我应用yamls文件时,我能够连接到数据库。我在GKE中使用的yamls几乎相同
secrets.yaml
apiVersion: v1
kind: Secret
metadata:
namespace: staging
name: postgres-secrets
type: Opaque
data:
MYAPPAPI_DATABASE_NAME: XXXENCODEDXXX
MYAPPAPI_DATABASE_USERNAME: XXXENCODEDXXX
MYAPPAPI_DATABASE_PASSWORD: XXXENCODEDXXX
pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
namespace: staging
name: db-data-pv
labels:
type: local
spec:
storageClassName: generic
capacity:
storage: 1Gi
accessModes:
- ReadWriteMany
hostPath:
path: "/var/lib/postgresql/data"
pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
namespace: staging
name: db-data-pvc
spec:
storageClassName: generic
accessModes:
- ReadWriteMany
resources:
requests:
storage: 500Mi
deployment.yaml
# Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: staging
labels:
app: postgres-db
name: postgres-db
spec:
replicas: 1
selector:
matchLabels:
app: postgres-db
template:
metadata:
labels:
app: postgres-db
spec:
containers:
- name: postgres-db
image: postgres:12.4
ports:
- containerPort: 5432
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgres-db
env:
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
name: postgres-secrets
key: MYAPPAPI_DATABASE_USERNAME
- name: POSTGRES_DB
valueFrom:
secretKeyRef:
name: postgres-secrets
key: MYAPPAPI_DATABASE_NAME
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secrets
key: MYAPPAPI_DATABASE_PASSWORD
volumes:
- name: postgres-db
persistentVolumeClaim:
claimName: db-data-pvc
svc.yaml
apiVersion: v1
kind: Service
metadata:
namespace: staging
labels:
app: postgres-db
name: postgresdb-service
spec:
type: ClusterIP
selector:
app: postgres-db
ports:
- port: 5432
似乎一切正常
然后我执行kubectl port-forward postgres-db-podname 5433:5432 -n staging
,当我试图连接它抛出
FATAL: role "myappuserdb" does not exist
这是来自GKE YAML
spec:
containers:
- env:
- name: POSTGRES_DB
valueFrom:
secretKeyRef:
key: MYAPPAPI_DATABASE_NAME
name: postgres-secrets
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
key: MYAPPAPI_DATABASE_USERNAME
name: postgres-secrets
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
key: MYAPPAPI_DATABASE_PASSWORD
name: postgres-secrets
更新2我将解释发生了什么以及我是如何解决这个问题的。
我第一次应用文件,kubectl apply -f k8s/
,在部署中,环境变量POSTGRES_USER引用了一个错误的秘密,MYAPPAPI_DATABASE_NAME,它应该引用MYAPPAPI_DATABASE_USERNAME。
在第一次之后,每次执行kubectl delete -f k8s/
时,资源都被删除了。但是,当我再次创建资源时,我在上一步中创建的数据没有被清除。
我删除了集群并创建了一个新的集群,一切正常。我需要检查是否有一种方法来清理kubernetes卷中的数据。
在您部署的env
规范中,您为POSTGRES_USER
分配了错误的值。您已分配值POSTGRES_USER = MYAPPAPI_DATABASE_NAME
.
但我认为应该是POSTGRES_USER = MYAPPAPI_DATABASE_USERNAME
。
env:
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
name: postgres-secrets
key: MYAPPAPI_DATABASE_NAME #<<<this is the value need to change>>>
请试试这个
env:
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
name: postgres-secrets
key: MYAPPAPI_DATABASE_USERNAME