Cannot connect to mongo container - java

I had a previous question that (I think at least) that more or less became useless as I managed to fix the errors I was presented with.. However my new error, is that I cannot seem to connect to mongodb from within my docker image
docker-compose.yml:
version: '3.1'
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mongo
ports:
- 8080:8080
mongo:
image: mongo
ports:
- '27017:27017'
networks:
mongo_net:
ipv4_address: 172.28.0.2
networks:
mongo_net:
driver: bridge
ipam:
driver: default
config:
-
subnet: 172.28.0.2/24
application.properties:
spring.data.mongodb.database=myDb
spring.data.mongodb.host=172.28.0.2
spring.data.mongodb.port=27017
And the actual error:
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.4.jar!/:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.4.jar!/:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.4.jar!/:na]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111]
Caused by: java.net.SocketTimeoutException: connect timed out

You’ve explicitly created a network in your docker-compose.yml file, and set your database to use that network. Docker Compose also creates a default network for you, and since your application doesn’t explicitly declare any networks, that attaches to only the default network. Then the two containers are on different networks and the one can’t reach the other.
The easiest solution here is to just delete all of the manual network configuration:
version: '3.1'
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
depends_on:
- mongo
ports:
- '8080:8080'
mongo:
image: mongo
ports:
- '27017:27017'
The name of the service block will be a valid DNS hostname, and in your configuration you can set spring.data.mongodb.host=mongo.

I agree David answer is right. But here is a takeaway, your configuration works too, I tried with my sample and here is the result.
Issue is your app is not attached to the network.
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mongo
ports:
- 8080:8080
networks:
- mongo_net
sample docker-compose.yml
version: '3.1'
services:
mongo-app:
image: barath-mongo
ports:
- "9000:9000"
depends_on:
- mongo
environment:
SPRING_DATA_MONGODB_PORT: 27017
SPRING_DATA_MONGODB_HOST: 172.28.0.2
SPRING_DATA_MONGODB_DATABASE: myDb
networks:
- mongo_net
mongo:
image: mongo
ports:
- '27017:27017'
networks:
mongo_net:
ipv4_address: 172.28.0.2
networks:
mongo_net:
driver: bridge
ipam:
driver: default
config:
-
subnet: 172.28.0.2/24
mongo container ip address:
$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ec2-user_mongo_1
172.28.0.2
docker network settings
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.28.0.2/24"
}
]
},
"Internal": false,
"Attachable": true,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"02b8b4148dd830eaddeb7e9ebd6305a6ae3c106bae5a495103c632aec7999274": {
"Name": "ec2-user_mongo-app_1",
"EndpointID": "885088d551888e1dec95b1c0e337c6a4b84f1bb2aebc4407963d3c0b4f6ec09d",
"MacAddress": "02:42:ac:1c:00:03",
"IPv4Address": "172.28.0.3/24",
"IPv6Address": ""
},
"3e4266fca3c8163412cc1c4733cad004aa0f366dc9fe30d03c7ecafe87b4e826": {
"Name": "ec2-user_mongo_1",
"EndpointID": "a6a72c7fc314a294c53d5c394ac1757702a0a95c588af2f730e971953dbbaa5f",
"MacAddress": "02:42:ac:1c:00:02",
"IPv4Address": "172.28.0.2/24",
"IPv6Address": ""
}
},
output :
ongo-app_1 | 2019-01-28 17:07:29.710 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:1}] to 172.28.0.2:27017
mongo-app_1 | 2019-01-28 17:07:29.735 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=172.28.0.2:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=20314562}
mongo-app_1 | 2019-01-28 17:07:29.742 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.cluster : Discovered cluster type of STANDALONE
mongo-app_1 | 2019-01-28 17:07:30.387 INFO 1 --- [ main] com.barath.app.service.CustomerService : Saving the customer with customer details com.barath.app.document.Customer#37654521
mongo_1 | 2019-01-28T17:07:30.488+0000 I NETWORK [listener] connection accepted from 172.28.0.3:56250 #2 (2 connections now open)
mongo_1 | 2019-01-28T17:07:30.491+0000 I NETWORK [conn2] received client metadata from 172.28.0.3:56250 conn2: { driver: { name: "mongo-java-driver", version: "3.8.2" }, os: { type: "Linux", name: "Linux", architecture: "amd64", version: "4.14.77-81.59.amzn2.x86_64" }, platform: "Java/Oracle Corporation/1.8.0_191-b12" }
mongo-app_1 | 2019-01-28 17:07:30.497 INFO 1 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:2}] to 172.28.0.2:27017
mongo_1 | 2019-01-28T17:07:30.576+0000 I STORAGE [conn2] createCollection: myDb.customer with generated UUID: 6bd5b022-16b6-4a04-96b0-d94988155a53
mongo-app_1 | 2019-01-28 17:07:31.514 INFO 1 --- [ main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
mongo-app_1 | 2019-01-28 17:07:31.879 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
mongo-app_1 | 2019-01-28 17:07:32.372 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
mongo-app_1 | 2019-01-28 17:07:32.432 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
mongo-app_1 | 2019-01-28 17:07:32.522 INFO 1 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
mongo-app_1 | 2019-01-28 17:07:32.977 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9000 (http) with context path ''
mongo-app_1 | 2019-01-28 17:07:32.984 INFO 1 --- [ main] com.barath.app.Application : Started Application in 11.151 seconds (JVM running for 13.149)

Related

How to connect to docker-compose port from docker and locally?

I am using spring boot 2.5.3 and postgreSQL for backend.
I want this app to run on localhost:5000/api/v1/customers as well as from docker-compose.
application.properties:
server.port=5000
#Database setup
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://localhost:5432/customers
spring.datasource.username=postgres
spring.datasource.password=postgres
This works with localhost, with mvn spring-boot:run
But, when I use the following application.properties settings from localhost to db
server.port=5000
#Database setup
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://db:5432/customers
spring.datasource.username=postgres
spring.datasource.password=postgres
Dockerfile
FROM maven:3.8.1-openjdk-11-slim
COPY ./target/customer-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
docker-compose.yml
version: '3.1'
services:
app:
container_name: customer-container
image: customer-image:v1
build: ./
ports:
- "5000:5000"
depends_on:
- db
db:
image: postgres
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=customers
I cannot connect to localhost:5000/api/v1/customers after mvn spring-boot:run
Error:
org.postgresql.util.PSQLException: Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:303) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:223) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.Driver.makeConnection(Driver.java:465) ~[postgresql-42.2.23.jar:42.2.23]
at org.postgresql.Driver.connect(Driver.java:264) ~[postgresql-42.2.23.jar:42.2.23]
Tried to create a docker image docker build -t customer-image:v1 .
, and run docker-compose build docker-compose up there are no error.
Logs says it is running on port 5000.
customer-container | 2021-08-29 12:43:42.053 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 5000 (http)
customer-container | 2021-08-29 12:43:42.068 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
customer-container | 2021-08-29 12:43:42.069 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.50]
customer-container | 2021-08-29 12:43:42.189 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
customer-container | 2021-08-29 12:43:42.190 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1876 ms
customer-container | 2021-08-29 12:43:42.487 INFO 1 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
customer-container | 2021-08-29 12:43:42.567 INFO 1 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
customer-container | 2021-08-29 12:43:42.702 INFO 1 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
customer-container | 2021-08-29 12:43:42.827 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
customer-container | 2021-08-29 12:43:42.970 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
customer-container | 2021-08-29 12:43:42.995 INFO 1 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
customer-container | 2021-08-29 12:43:43.631 WARN 1 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
customer-container | 2021-08-29 12:43:43.631 WARN 1 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "customer" does not exist, skipping
customer-container | 2021-08-29 12:43:43.642 INFO 1 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
customer-container | 2021-08-29 12:43:43.656 INFO 1 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
customer-container | 2021-08-29 12:43:44.252 WARN 1 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
customer-container | 2021-08-29 12:43:44.991 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 5000 (http) with context path ''
customer-container | 2021-08-29 12:43:45.290 INFO 1 --- [ main] c.p.customer.CustomerApplication : Started CustomerApplication in 5.654 seconds (JVM running for 6.531)
This works localhost:5000/api/v1/customers when docker-compose is up.
Is there a way we can have condtional name for host in this line?Is there any other way?
spring.datasource.url=jdbc:postgresql://db:5432/customers
Since the host development environment and the container runtime environment are different, you can use environment variables to differentiate between them. Spring Boot knows how to set Spring properties from environment variables. So I'd recommend:
In your application.properties file, set spring.datasource.url to the localhost URL you'd use in development.
In your Compose setup, set the SPRING_DATASOURCE_URL environment variable to the name specific to that Compose setup
version: '3.8'
services:
db: { ... }
app:
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/customers
...
Do not create a separate Spring profile per environment; you would not want to recompile your jar file if you changed the database name or password, or deployed this in Kubernetes, or used a cloud-hosted database like Amazon RDS, or...
So, you want to be able to run both locally and from docker?
If that's the case, you need to extract the database connection string to an environment variable that you set at runtime
spring.datasource.url = ${DB_HOST}:${DB_PORT}/
spring.datasource.username = ${DB_USERNAME}
spring.datasource.password = ${DB_PASSWD}
Or you can introduce two different property files that get set from a Spring profile, which you also would set at runtime; Refer SPRING_PROFILES_ACTIVE environment variable
Based on what I see, you are not supposed to use localhost on spring.datasource.url because your docker is within the container itself, you should be using
jdbc:postgresql://host.docker.internal:5432/customers instead. For more details, you can view from this link https://docs.docker.com/desktop/windows/networking/#i-cannot-ping-my-containers
Is there a way we can have condtional name for host in this line?Is there any other way?
As for this, it would be prefered to set it as an environmetn variable on your docker compose file and connect using dbconn url
If you are using linux as your operating system on which you are running your docker , you can set this property
network_mode: host
on both the containers, this will attach your container's port to your localhost port.
You will need to remove the port forwarding config for this to work.

TestContainers embedded db cannot find tables

I have created a spring boot app with the following setup:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com</groupId>
<artifactId>ticket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ticket</name>
<description>ticketing microservice</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
<dependency>
<groupId>com.github.cliftonlabs</groupId>
<artifactId>json-simple</artifactId>
<version>3.1.1</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>3.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.14.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.playtika.testcontainers</groupId>
<artifactId>embedded-postgresql</artifactId>
<version>1.43</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
bootstrap-test.properties:
embedded.postgresql.enabled=true
embedded.postgresql.dockerImage=postgres
embedded.postgresql.user=docker
embedded.postgresql.password=docker
embedded.postgresql.schema=test_db
embedded.containers.forceShutdown=true
application-test.properties
spring.datasource.url=jdbc:postgresql://${embedded.postgresql.host}:${embedded.postgresql.port}/${embedded.postgresql.schema}
spring.datasource.username=${embedded.postgresql.user}
spring.datasource.password=${embedded.postgresql.password}
spring.jpa.hibernate.ddl-auto=create
My simple test class:
#AutoConfigureMockMvc
#ActiveProfiles("test")
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TicketControllerTest {
#LocalServerPort
private int port;
#Autowired
private TestRestTemplate restTemplate;
#Test
public void getInfoTest() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/tickets/info",
String.class)).contains("ghix-ticket");
}
#Test
public void postTicket() throws Exception {
UserTicket rt = new UserTicket();
rt.setDetails("Details test");
rt.setSubject("subject test");
rt.setCreatedBy("1");
rt.setCategory("Verify Death");
rt.setType("Document Verification");
rt.setRole("2025");
TkmTickets responseT = this.restTemplate.postForObject("http://localhost:" + port + "/tickets/",
rt, TkmTickets.class);
System.out.println(responseT.getId());
assertThat(responseT.getDescription()).isEqualTo("Details test");
}
}
Things look good on startup:
10:23:46.877 [main] DEBUG org.springframework.core.env.StandardEnvironment - Activating profiles [test]
10:23:46.881 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}
2021-04-07 10:23:47.419 INFO 27556 --- [ main] EmbeddedPostgreSQLBootstrapConfiguration : Starting postgresql server. Docker image: postgres
2021-04-07 10:23:47.469 INFO 27556 --- [ main] o.t.d.DockerClientProviderStrategy : Loaded org.testcontainers.dockerclient.UnixSocketClientProviderStrategy from ~/.testcontainers.properties, will try it first
2021-04-07 10:23:47.833 INFO 27556 --- [ main] o.t.d.UnixSocketClientProviderStrategy : Accessing docker with local Unix socket
2021-04-07 10:23:47.833 INFO 27556 --- [ main] o.t.d.DockerClientProviderStrategy : Found Docker environment with local Unix socket (unix:///var/run/docker.sock)
2021-04-07 10:23:47.949 INFO 27556 --- [ main] org.testcontainers.DockerClientFactory : Docker host IP address is localhost
2021-04-07 10:23:47.991 INFO 27556 --- [ main] org.testcontainers.DockerClientFactory : Connected to docker:
Server Version: 20.10.3
API Version: 1.41
Operating System: Docker Desktop
Total Memory: 1989 MB
2021-04-07 10:23:48.250 INFO 27556 --- [ main] o.t.utility.RegistryAuthLocator : Credential helper/store (docker-credential-desktop) does not have credentials for quay.io
2021-04-07 10:23:48.758 INFO 27556 --- [ main] org.testcontainers.DockerClientFactory : Ryuk started - will monitor and terminate Testcontainers containers on JVM exit
2021-04-07 10:23:48.758 INFO 27556 --- [ main] org.testcontainers.DockerClientFactory : Checking the system...
2021-04-07 10:23:48.759 INFO 27556 --- [ main] org.testcontainers.DockerClientFactory : ✔︎ Docker server version should be at least 1.6.0
2021-04-07 10:23:48.865 INFO 27556 --- [ main] org.testcontainers.DockerClientFactory : ✔︎ Docker environment should have more than 2GB free disk space
2021-04-07 10:23:48.873 INFO 27556 --- [ main] 🐳 [postgres:latest] : Creating container for image: postgres:latest
2021-04-07 10:23:49.006 INFO 27556 --- [ main] 🐳 [postgres:latest] : Starting container with ID: 131caba247444daf5c6cc0cff99e8c3ebfc658d53c36d771aeaa2ba6e9bad4c6
2021-04-07 10:23:49.312 INFO 27556 --- [ main] 🐳 [postgres:latest] : Container postgres:latest is starting: 131caba247444daf5c6cc0cff99e8c3ebfc658d53c36d771aeaa2ba6e9bad4c6
2021-04-07 10:23:50.425 INFO 27556 --- [ main] 🐳 [postgres:latest] : Container postgres:latest started in PT2.966109S
2021-04-07 10:23:50.426 INFO 27556 --- [ main] EmbeddedPostgreSQLBootstrapConfiguration : Started postgresql server. Connection details: {embedded.postgresql.port=55070, embedded.postgresql.host=localhost, embedded.postgresql.schema=test_db, embedded.postgresql.user=docker, embedded.postgresql.password=docker}, JDBC connection url: jdbc:postgresql://localhost:55070/test_db
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.4)
2021-04-07 10:23:50.550 INFO 27556 --- [ main] c.g.ticket.TicketControllerTest : The following profiles are active: test
2021-04-07 10:23:51.041 INFO 27556 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-04-07 10:23:51.087 INFO 27556 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 39 ms. Found 2 JPA repository interfaces.
2021-04-07 10:23:51.173 INFO 27556 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=648ef21c-f385-3b5a-a247-511006c4b8be
2021-04-07 10:23:51.199 INFO 27556 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method EmbeddedPostgreSQLDependenciesAutoConfiguration.datasourceDependencyPostProcessor is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2021-04-07 10:23:51.564 INFO 27556 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2021-04-07 10:23:51.574 INFO 27556 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-04-07 10:23:51.575 INFO 27556 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.44]
2021-04-07 10:23:52.114 INFO 27556 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-04-07 10:23:52.114 INFO 27556 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1560 ms
2021-04-07 10:23:52.320 INFO 27556 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-04-07 10:23:52.384 INFO 27556 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.29.Final
2021-04-07 10:23:52.524 INFO 27556 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-04-07 10:23:52.619 INFO 27556 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-04-07 10:23:52.738 INFO 27556 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
However shorty after that I see it start to tell me it cannot find the tables in the DB:
2021-04-07 10:23:52.778 INFO 27556 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2021-04-07 10:23:52.868 INFO 27556 --- [ main] o.h.e.boot.internal.EnversServiceImpl : Envers integration enabled? : true
2021-04-07 10:23:54.110 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2021-04-07 10:23:54.111 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : relation "tkm_ticket_tasks" does not exist, skipping
2021-04-07 10:23:54.112 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2021-04-07 10:23:54.113 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : relation "tkm_ticket_tasks" does not exist, skipping
2021-04-07 10:23:54.114 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2021-04-07 10:23:54.114 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : relation "tkm_ticket_tasks_aud" does not exist, skipping
2021-04-07 10:23:54.116 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2021-04-07 10:23:54.116 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : relation "tkm_tickets" does not exist, skipping
2021-04-07 10:23:54.117 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2021-04-07 10:23:54.117 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : relation "tkm_tickets" does not exist, skipping
2021-04-07 10:23:54.118 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2021-04-07 10:23:54.118 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : relation "tkm_tickets_aud" does not exist, skipping
2021-04-07 10:23:54.120 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2021-04-07 10:23:54.120 WARN 27556 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : relation "tkm_workflows" does not exist, skipping
I have a look at the db when debugging and sure enough no tables exist on that postgres container, am I missing something in terms of setup, my understanding was that:
spring.jpa.hibernate.ddl-auto=create
Along with the data in data.sql will be all the setup required to create and populate my tables within the DB container.
Here is my dockerFile:
FROM openjdk:8
ADD target/ghix-ticket-0.0.1-SNAPSHOT.jar ghix-ticket-0.0.1-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "ghix-ticket-0.0.1-SNAPSHOT.jar"]
and my dockercompose:
version: "3"
services:
db:
image: postgres
#network_mode: bridge
container_name: db
volumes:
- postgres-data:/var/lib/postgresql/data
expose:
- 5432
ports:
- 5432:5432
environment:
- POSTGRES_PASSWORD=docker
- POSTGRES_USER=docker
- POSTGRES_DB=docker
restart: unless-stopped
# This is my rest api app*****************************************
ghix-ticket:
image: ghix-ticket
#network_mode: bridge
container_name: ghix-ticket
expose:
- 8080
ports:
- 8081:8080
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://db/docker
SPRING_DATASOURCE_USERNAME: docker
SPRING_DATASOURCE_PASSWORD: docker
depends_on:
- db
volumes:
- /Users/mcerlane_w/dev/:/var/tmp
restart: unless-stopped
volumes:
postgres-data:
However this is coming from when I am running my tests from IDE or when I run via:
mvn test -Dspring-boot.run.profiles=test
Log from Postgres container:
The files belonging to this database system will be owned by user
"postgres".
This user must also own the server process.
The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".
Data page checksums are disabled.
fixing permissions on existing directory /var/lib/postgresql/data ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Etc/UTC
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok
initdb: warning: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.
Success. You can now start the database server using:
pg_ctl -D /var/lib/postgresql/data -l logfile start
waiting for server to start....2021-04-07 17:55:15.130 UTC [48] LOG: starting PostgreSQL 13.2 (Debian 13.2-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
2021-04-07 17:55:15.131 UTC [48] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2021-04-07 17:55:15.132 UTC [49] LOG: database system was shut down at 2021-04-07 17:55:14 UTC
2021-04-07 17:55:15.134 UTC [48] LOG: database system is ready to accept connections
done
server started
CREATE DATABASE
/usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
2021-04-07 17:55:15.339 UTC [48] LOG: received fast shutdown request
2021-04-07 17:55:15.339 UTC [48] LOG: aborting any active transactions
waiting for server to shut down....2021-04-07 17:55:15.342 UTC [48] LOG: background worker "logical replication launcher" (PID 55) exited with exit code 1
2021-04-07 17:55:15.342 UTC [50] LOG: shutting down
2021-04-07 17:55:15.347 UTC [48] LOG: database system is shut down
done
server stopped
PostgreSQL init process complete; ready for start up.
2021-04-07 17:55:15.459 UTC [1] LOG: starting PostgreSQL 13.2 (Debian 13.2-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
2021-04-07 17:55:15.459 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
2021-04-07 17:55:15.460 UTC [1] LOG: listening on IPv6 address "::", port 5432
2021-04-07 17:55:15.460 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2021-04-07 17:55:15.462 UTC [76] LOG: database system was shut down at 2021-04-07 17:55:15 UTC
2021-04-07 17:55:15.466 UTC [1] LOG: database system is ready to accept connections

Helm chart spring boot application shut down immediately after starting

I was trying out spring boot microservice deployment on kubernetes cluster using Helm Chart. But I noticed a strange issue that my spring boot application start but it shutdown immediately after
Here are the logs
Started JhooqK8sApplication in 3.431 seconds (JVM running for 4.149)
2020-06-25 20:57:24.460 INFO 1 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-06-25 20:57:24.469 INFO 1 --- [extShutdownHook] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#548a102f{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
2020-06-25 20:57:24.470 INFO 1 --- [extShutdownHook] org.eclipse.jetty.server.session : node0 Stopped scavenging
2020-06-25 20:57:24.474 INFO 1 --- [extShutdownHook] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'
2020-06-25 20:57:24.493 INFO 1 --- [extShutdownHook] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext#56528192{application,/,[file:///tmp/jetty-docbase.4637295322181051129.8080/],UNAVAILABLE}
Spring Boot Version : 2.2.7.RELEASE
Docker Hub Public image for spring boot : rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty
One strange thing which i noticed when i use kubectl command manually to create deployment and service spring boot deployments goes perfectly fine.
vagrant#kmaster:~$ kubectl create deployment demo --image=rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty
vagrant#kmaster:~$ kubectl expose deployment demo --type=LoadBalancer --name=demo-service --external-ip=1.1.1.1 --port=8080
(I followed this guide for deploying spring boot on kubernete - Deploy spring boot on kubernetes cluster)
I am just wodering is there something wrong with spring boot or my helm setup?
Here is my helm templates -
---
# Source: springboot/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: RELEASE-NAME-springboot
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
---
# Source: springboot/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: RELEASE-NAME-springboot
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
spec:
type: ClusterIP
ports:
- port: 80
targetPort: http
protocol: TCP
name: http
selector:
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
---
# Source: springboot/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: RELEASE-NAME-springboot
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
template:
metadata:
labels:
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
spec:
serviceAccountName: RELEASE-NAME-springboot
securityContext:
{}
containers:
- name: springboot
securityContext:
{}
image: "rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty"
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{}
---
# Source: springboot/templates/tests/test-connection.yaml
apiVersion: v1
kind: Pod
metadata:
name: "RELEASE-NAME-springboot-test-connection"
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
annotations:
"helm.sh/hook": test-success
spec:
containers:
- name: wget
image: busybox
command: ['wget']
args: ['RELEASE-NAME-springboot:80']
restartPolicy: Never
2020-06-25 20:57:24.469 INFO 1 --- [extShutdownHook] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#548a102f{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
ports:
- name: http
containerPort: 80
It appears the liveness probe (configured to contact the port named http) is killing your Pod since your container appears to be listening on :8080 but you've told kubernetes that it's listening on :80
Since a kubectl created deployment will not have any such specificity, kubernetes won't use a liveness probe and there you are
You can usually configure the spring application via an environment variable if you want to test that theory:
containers:
- name: springboot
env:
- name: SERVER_PORT
value: '80'
# and its friend, which is the one that
# you should be using for liveness and readiness
- name: MANAGEMENT_SERVER_PORT
value: '8080'
securityContext:
{}
image: "rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty"
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
protocol: TCP

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure when trying to build spring boot docker image

I am trying to build my docker image for my spring boot application but keep encountering this error:
:: Spring Boot :: (v2.2.5.RELEASE)
2020-05-31 02:18:39.820 INFO 63 --- [ main] c.g.Apollo.ApolloApplicationTests : Starting ApolloApplicationTests on 4b284b60945e with PID 63 (started by root in /build)
2020-05-31 02:18:39.838 INFO 63 --- [ main] c.g.Apollo.ApolloApplicationTests : No active profile set, falling back to default profiles: default
2020-05-31 02:18:42.208 INFO 63 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 02:18:42.467 INFO 63 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 216ms. Found 3 JPA repository interfaces.
2020-05-31 02:18:44.902 INFO 63 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-31 02:18:46.575 ERROR 63 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.2.jar:na]
Terminal when successfully running in intellij:
:: Spring Boot :: (v2.2.5.RELEASE)
2020-05-31 01:04:39.322 INFO 19524 --- [ restartedMain] c.g.Apollo.ApolloApplication : Starting ApolloApplication on asd-PC with PID 19524 (C:\Projects\Apollo\target\classes started by asd in C:\Projects\Apollo)
2020-05-31 01:04:39.324 INFO 19524 --- [ restartedMain] c.g.Apollo.ApolloApplication : No active profile set, falling back to default profiles: default
2020-05-31 01:04:39.354 INFO 19524 --- [ restartedMain] o.s.b.devtools.restart.ChangeableUrls : The Class-Path manifest attribute in C:\Users\asd\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-05-31 01:04:39.354 INFO 19524 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-05-31 01:04:39.354 INFO 19524 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-05-31 01:04:39.785 INFO 19524 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 01:04:39.846 INFO 19524 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 54ms. Found 3 JPA repository interfaces.
2020-05-31 01:04:40.214 INFO 19524 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-05-31 01:04:40.220 INFO 19524 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-31 01:04:40.221 INFO 19524 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-05-31 01:04:40.293 INFO 19524 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-31 01:04:40.293 INFO 19524 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 939 ms
2020-05-31 01:04:40.365 INFO 19524 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-31 01:04:40.702 INFO 19524 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-31 01:04:40.731 INFO 19524 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-31 01:04:40.800 INFO 19524 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-05-31 01:04:40.919 INFO 19524 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-31 01:04:41.006 INFO 19524 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-05-31 01:04:41.407 INFO 19524 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-31 01:04:41.413 INFO 19524 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-31 01:04:41.650 WARN 19524 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-31 01:04:41.717 INFO 19524 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-31 01:04:41.967 INFO 19524 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-05-31 01:04:41.995 INFO 19524 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-05-31 01:04:41.997 INFO 19524 --- [ restartedMain] c.g.Apollo.ApolloApplication : Started ApolloApplication in 2.911 seconds (JVM running for 3.899)
My Dockerfile:
FROM maven:3.6.3-jdk-11-slim AS MAVEN_BUILD
COPY pom.xml /build/
COPY src /build/src/
WORKDIR /build/
RUN mvn package
FROM openjdk:11-jre-alpine
WORKDIR /app
COPY --from=MAVEN_BUILD /build/target/*.war /app/app.war
ENTRYPOINT ["java", "-jar", "app.war"]
My application.properties:
## GraphQL SPQR ##
server.port=8080
graphql.spqr.gui.enabled=true
graphql.spqr.http.endpoint=/graphql
graphql.spqr.ws.endpoint=/graphql
## Database Properties ##
spring.datasource.url=jdbc:mysql://localhost:3306/innodb
spring.datasource.username=root
spring.datasource.password=1234
My application works when I build and run the project in Intellij but not when I try and build my docker image. I am using MySQL and have just been connecting on localhost on port 3306.
The error message seems to indicate the issue is failing to connect to the database. From your settings, it appears that you are trying to connect to the DB using localhost:3306. That will not work when you are running the application in a container because docker creates its own network which is separate from you machine’s network. So, localhost in the container does not refer to your machine.
You need to instead setup a docker network that will allow your container to access the database in a specific IP address.
Here is an article with the specifics:
https://nickjanetakis.com/blog/docker-tip-35-connect-to-a-database-running-on-your-docker-host
Note that I have assumed from your post, that the DB is installed in your host machine. If it is not and the DB is running in its own container, the you need to create a docker network and attach both containers to that network.
I had the same issue and resolved it by changing localhost to the service name on which MySQL was running.
Below is my docker-compose and application.properties files
docker-compose.yml
version: '3.8'
services:
app:
container_name: tvms
build:
context: .
dockerfile: Dockerfile
tty: true
volumes:
- ../..:/workspaces:cached
ports:
- 8990:8990
networks:
- impaq
links:
- db:db
db:
image: percona:8.0
privileged: true
restart: always
container_name: standalone-mysql
environment:
MYSQL_ROOT_PASSWORD: ****
volumes:
- perconadata:/var/lib/mysql
ports:
- 3306:3306
networks:
- impaq
networks:
impaq:
volumes:
perconadata:
application.propeties
#datasource
spring.datasource.url=jdbc:mysql://db:3306/db_name
spring.datasource.username=root
spring.datasource.password=*****
For me below solution worked
change your datasource url from
This:
spring.datasource.url=jdbc:mysql://localhost:3306/innodb
To:
spring.datasource.url=jdbc:mysql://localhost:3306/innodb?useSSL=false

What is the correct jdbc for Spring boot for containerized postgressql

I have a Spring boot app that is containerized and published to the docker hub. I have this docker-copmse.yml:-
version: '3.1'
services:
postgres:
image: postgres
container_name: postgres
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=mydb
profile_back:
container_name: profile_back
image: madsum/profile_back
ports:
- "8080:8080"
depends_on:
- postgres
My spring boot application.propertiese:-
#spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.url=jdbc:postgresql://postgres:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
I don't know what is the correct spring.datasource.url. I tried both jdbc:postgresql://localhost:5432/mydb and jdbc:postgresql://postgres:5432/mydb .Both give connection error. Btw, container runs perfectly. I can verify by it as docker exec -it --user postgres dbpostgresql sh . I can see the database created. What is the correct way to connect it?
Updated question:-
I am using flyway. Here is the exception now:-
ound 1 JPA repository interfaces.
2020-03-06 09:33:01.939 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-06 09:33:01.949 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-06 09:33:01.949 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-06 09:33:01.997 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-06 09:33:01.998 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1180 ms
2020-03-06 09:33:02.118 INFO 1 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.0.8 by Redgate
2020-03-06 09:33:02.124 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-06 09:33:02.127 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
2020-03-06 09:33:02.130 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-03-06 09:33:02.141 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-06 09:33:02.145 ERROR 1 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.4.RELEASE.jar!/:5.2.4.RELEASE]
Carefully reading the exception, gives you a valuable hint:
Invocation of init method failed; nested exception is
java.lang.RuntimeException: Driver org.postgresql.Driver claims to not
accept jdbcUrl,
jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 2020-03-06
So it seems your application tries to connect to an in-memory H2 database and not to PostgreSQL.
Do you maybe use different profiles for your application and forgot to set the production profile? Otherwise, you can get rid of the H2 dependency in your pom.xml/build.gradle if you don't need it
Try using 127.0.0.1 instead of localhost

Categories

Resources