K8s部署服务连接托管PostgreSQL时pq加密panic问题排查
问题
我正在测试如下数据库插入语句,该语句在本地运行正常,但部署到连接托管数据库的Kubernetes集群后失效:
func Insert(w http.ResponseWriter, r *http.Request) { db := dbConn() //If it's a post request, assign a variable to the value returned in each field of the New page. if r.Method == "POST" { email := r.FormValue("email") socialNetwork := r.FormValue("social_network") socialHandle := r.FormValue("social_handle") createdOn := time.Now().UTC() //prepare a query to insert the data into the database insForm, err := db.Prepare(`INSERT INTO public.users(email, social_network, social_handle) VALUES ($1,$2, $3)`) //check for and handle any errors CheckError(err) //execute the query using the form data _, err = insForm.Exec(email, socialNetwork, socialHandle) CheckError(err) //print out added data in terminal log.Println("INSERT: email: " + email + " | social network: " + socialNetwork + " | social handle : " + socialHandle + " | created on: " + createdOn.String() + " | createdOn is type: " + reflect.TypeOf(createdOn).String()) sendThanks(socialHandle, email) } defer db.Close() //redirect to the index page http.Redirect(w, r, "/thanks", 301) }
已配置如下Deployment及对应Secret对象:
apiVersion: apps/v1 kind: Deployment metadata: name: novvsworld namespace: novvsworld spec: replicas: 1 selector: matchLabels: app: novvsworld template: metadata: labels: app: novvsworld spec: containers: - name: novvsworld image: my.registry.com/registry/novvsworld:latest resources: limits: memory: "128Mi" cpu: "500m" ports: - containerPort: 3000 env: - name: DBHOST valueFrom: secretKeyRef: name: novvworld-secrets key: DBHOST - name: DBPORT valueFrom: secretKeyRef: name: novvworld-secrets key: DBPORT - name: DBUSER valueFrom: secretKeyRef: name: novvworld-secrets key: DBUSER - name: DBPASS valueFrom: secretKeyRef: name: novvworld-secrets key: DBPASS - name: DBSSLMODE valueFrom: secretKeyRef: name: novvworld-secrets key: DBSSLMODE - name: SENDGRID_API_KEY valueFrom: secretKeyRef: name: novvworld-secrets key: SENDGRID_API_KEY
Secret文件中DBSSLMODE的值当前设为"disabled"。
通过前端输入数据测试插入语句时,返回如下panic:
022/08/15 18:50:58 http: panic serving 10.244.0.38:47590: pq: no pg_hba.conf entry for host "167.172.231.113", user "novvsworld", database "novvsworld", no encryption
请问我是否遗漏了加密相关的额外配置?设置sslmode为disabled难道不应该绕过该问题吗?
回答
核心原因:托管PostgreSQL服务通常强制要求加密连接,哪怕你设置
sslmode=disabled也无法绕过。错误提示说明数据库端的pg_hba.conf里没有允许无加密连接的条目,针对你的客户端IP和用户配置的是必须加密连接。正确的SSL模式配置:
- 将Secret中的
DBSSLMODE值改为require——这是托管PostgreSQL最常用的模式,强制使用SSL加密连接,且不验证服务器证书。 - 如果托管服务提供了CA证书,建议改为
verify-ca或verify-full,同时在数据库连接字符串中指定sslrootcert路径,进一步确保连接安全性。
- 将Secret中的
额外检查点:
- 确认Kubernetes集群的IP段已被添加到托管数据库的白名单中,这也是连接失败的常见诱因。
- 检查
dbConn()函数是否正确读取了DBSSLMODE环境变量,确保连接字符串里包含sslmode参数,示例格式如下:postgres://user:pass@host:port/dbname?sslmode=require
内容的提问来源于stack exchange,提问作者eomolo
相关产品推荐
相关产品推荐

