如何在Kubernetes上部署使用postgres数据库的Spring Boot应用程序?

如何在Kubernetes上部署使用postgres数据库的Spring Boot应用程序?

问题描述:

我使用此命令部署了我的spring boot应用程序

I used this command to deploy my spring boot application

sudo kubectl run mykubernetes-springboot 
--image=glgelopfalcon/springboot_docker_maven:0.0.1-SNAPSHOT --port=8080

已创建部门,但是当我通过

Deplyment is created but when i check logs by

kubectl logs pod podname

它给出了例外

Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

我在本地计算机上安装了postgres.

I installed postgres on my local machine.

测试是否有答案 postgres.yaml

Test for semah answer postgres.yaml

kind: Service
apiVersion: v1
metadata:
  name: postgres-svc
  namespace: default
spec:
  type: ExternalName
  externalName: 10.0.2.2

kubectl get svc提供

kubectl get svc gives

postgres-svc       ExternalName   <none>           10.0.2.2      <none>           2m12s

Spring Boot应用程序部署日志提供

Spring boot app deployement logs give

IOException occurred while connecting to postgres-svc.external.svc:5432
java.net.UnknownHostException: postgres-svc.external.svc

如果您尝试连接到安装在本地计算机而不是kubernetes中的数据库,则出现此错误是正常现象,因为pod内的localhost并不意味着您的本地机器,那么您能知道您的数据库在哪里运行吗?

If you are trying to connect to DB installed on your local machine and not in kubernetes it is normal to have this error because localhost inside pod this not means your local machine , so can you tell where your db is running ?

在确认您在本地运行时尝试此操作:

try this as you confirmed that you run in local :

apiVersion: v1
kind: Service
metadata:
name: mysql-db-svc
spec:
ports:
- port: 5432

并将端点添加到此服务:

and add endpoint to this service :

apiVersion: v1
kind: Endpoints
metadata:
name: mysql-db-svc
subsets:
- addresses:
 - ip: 10.0.2.2
 ports:
 - port: 5432

然后使用:

url=jdbc:postgresql://mysql-db-svc/databasename