【发布时间】:2021-06-03 20:29:33
【问题描述】:
在我的 K8 集群中,我在同一个命名空间中有两个部署。一个部署用于 Database-Postgres,另一个部署用于 Tomcat。 Tomcat 应该可以从外部访问,因此我已经配置了“NodePort”服务,并且对于内部通信,我通过公开 Postgres 的端口(即 5432)创建了一个“ClusterIP”服务。部署完所有内容后,我希望 Tomcat pod 与 Postgres pod 进行通信。但是当我从 Tomcat pod 中“curl postgres-service:5432”时,我收到“Connection denied”消息。有没有配置错误?
apiVersion: v1
kind: Service
metadata:
name: tomcat-service
namespace: application
labels:
app: application-tomcat
spec:
type: NodePort
ports:
- name: tomcat-port
targetPort: 80
port: 80
selector:
app: application-tomcat
---
apiVersion: v1
kind: Service
metadata:
name: postgres-service
namespace: application
labels:
app: application-postgres
spec:
ports:
- port: 5432
name: postgres-port
selector:
app: application-postgres
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: application-tomcat-deployment
namespace: application
labels:
app: application-tomcat
spec:
replicas: 1
selector:
matchLabels:
app: application-tomcat
template:
metadata:
labels:
app: application-tomcat
spec:
containers:
- name: application-container
image: tomcat
command:
- sleep
- "infinity"
ports:
- containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: application
name: application-postgres-deployment
labels:
app: application-postgres
spec:
replicas: 1
selector:
matchLabels:
app: application-postgres
template:
metadata:
labels:
app: application-postgres
spec:
containers:
- name: postgres
image: postgres
command:
- sleep
- "infinity"
ports:
- containerPort: 5432
name: postgredb
Postgres pod 正在侦听端口“5432”并且数据库正在运行。
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN -
tcp6 0 0 :::5432 :::* LISTEN -
命名空间中的资源
$ kubectl get all -n application
NAME READY STATUS RESTARTS AGE
pod/application-postgres-deployment-694869cd5d-wrhzr 1/1 Running 0 9m9s
pod/application-tomcat-deployment-6db75ffb6d-ds8fr 1/1 Running 0 9m9s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/postgres-service ClusterIP 10.32.0.207 <none> 5432/TCP 9m9s
service/tomcat-service NodePort 10.32.0.59 <none> 80:31216/TCP 9m9s
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/application-postgres-deployment 1/1 1 1 9m9s
deployment.apps/application-tomcat-deployment 1/1 1 1 9m9s
NAME DESIRED CURRENT READY AGE
replicaset.apps/application-postgres-deployment-694869cd5d 1 1 1 9m9s
replicaset.apps/application-tomcat-deployment-6db75ffb6d 1 1 1 9m9s
【问题讨论】:
-
您不需要手动/显式创建
ClusterIP类型的Service。NodePort服务在内部创建了一个ClusterIP服务,可用于内部通信。 -
我省略了 ClusterIP 类型的服务,但它只会创建一个 NodePort 服务。那么如何在 Tomcat 中指定主机名以便与 Postgres pod 通信呢?那么我应该使用什么名称从 Tomcat pod 中“卷曲”?
-
您可以使用
curl http:servicename/这样的服务名称访问pod -
请编辑问题以在此处添加详细信息。
-
为什么你的容器运行
command: [sleep, infinity]?这肯定会导致“连接被拒绝”错误,因为数据库和 Web 服务器进程实际上并未运行。
标签: postgresql tomcat kubernetes kubernetes-service