Rest Api application can't connect to postgres db in the same Kubernetes pod

8/29/2019

Hi i receive the following error:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [file.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I have a kubernetes cluster where I defined a pod with two containers, one is the postgres db and the other one is a java rest-api application. I'm unable to connect to the db from the application. I'm tring to connect to the postgres db using spring, this is my xml file configuration:

<!-- JPA Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5432/dbName" />
    <property name="username" value="postgres"/>
    <property name="password" value="postgres"/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.my-package.it.name.db" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <!--<property name="showSql" value="true" />-->
        </bean>
    </property>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
</bean>

Well thanks for your time and help

-- lello-sca87
kubernetes
postgresql
spring

1 Answer

8/30/2019

What you should do is, create deployment for your database and then service, which targets this deployment and then ping using this service:

apiVersion: v1
kind: Service
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  type: NodePort
  ports:
   - port: 5432
  selector:
   app: postgres

If you want me to reproduce it on your files, please provide it in your post. You can check this article.

-- muscat
Source: StackOverflow