Issue
I am trying to create two different deployments using kubernetes, one for a spring boot project and another one for mongo db. I want the spring boot project to connect to mongo. Here is my properties file:
server:
port: 8081
spring:
data:
mongodb:
host: mongo-service
port: 27017
database: inventory
And here is the .yml file I am using for kubernetes:
apiVersion: apps/v1
kind: Deployment
metadata:
name: inventory
labels:
app: inventory
spec:
selector:
matchLabels:
app: inventory
template:
metadata:
labels:
app: inventory
spec:
containers:
- image: carlospalma03/inventory_java-api:version7
name: inventory-api
ports:
- containerPort: 8081
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongo
labels:
app: mongo
spec:
selector:
matchLabels:
app: mongo
template:
metadata:
labels:
app: mongo
spec:
containers:
- image: mongo
name: mongo-db
ports:
- containerPort: 27017
---
apiVersion: v1
kind: Service
metadata:
name: mongo-service
labels:
run: mongo-service
spec:
ports:
- port: 27017
protocol: TCP
selector:
app: mongo-service
I get the following exception on the spring boot side:
Exception in monitor thread while connecting to server mongo-db:27017
Does anybody know what's the proper name I should use for the mongo-db service so that the spring boot project can communicate with it?
I am trying to use the name of the kubernetes service I created to enable communication but something tells me that there's a trick to how spring boot names the other pods.
Solution
Alright, a couple things here, first of all I had to create two services, not just one. The service associated to the spring boot deployment talks with other pods in the kubernetes cluster.
apiVersion: apps/v1
kind: Deployment
metadata:
name: inventory
labels:
app: inventory
spec:
selector:
matchLabels:
app: inventory
template:
metadata:
labels:
app: inventory
spec:
containers:
- image: carlospalma03/inventory_java-api:version9
name: inventory-api
ports:
- containerPort: 8081
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongo
labels:
app: mongo
spec:
selector:
matchLabels:
app: mongo
template:
metadata:
labels:
app: mongo
spec:
containers:
- image: mongo
name: mongo-db
ports:
- containerPort: 27017
---
apiVersion: v1
kind: Service
metadata:
name: inventory-service
labels:
run: inventory-service
spec:
ports:
- port: 8081
targetPort: 8081
protocol: TCP
selector:
app: inventory
type: NodePort
---
apiVersion: v1
kind: Service
metadata:
name: mongo-service
labels:
run: mongo-service
spec:
ports:
- port: 27017
targetPort: 27017
protocol: TCP
selector:
app: mongo
Secondly I had to use the spring.data.mongo.db.uri property inside the spring boot project like this:
server:
port: 8081
spring:
data:
mongodb:
uri: mongodb://mongo-service:27017/inventory
Answered By - carlos palma
Answer Checked By - Marilyn (JavaFixing Volunteer)