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.
Related
The problem is when spring boot app gets triggered by live reload. Then it usually crashes a whole docker image. it's not on every live reload happens, but it happens very often.
docker-compose.yml
version: "3.7"
services:
app:
image: youtube-spring-boot-image
ports:
- "8080:8080"
depends_on:
- postgres
restart: always
postgres:
image: postgres:latest
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- "5432:5432"
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=posts
restart: unless-stopped
volumes:
postgres-data:
application.yml
spring:
devtools:
restart:
poll-interval: 2s
quiet-period: 1s
data:
web:
pageable:
one-indexed-parameters: true
max-page-size: 50
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
devtools:
remote:
secret: "mysecret"
datasource:
username: postgres
url: jdbc:postgresql://postgres:5432/posts
password: postgres
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: 'true'
hibernate:
ddl-auto: update
show-sql: 'true'
mvc:
throw-exception-if-no-handler-found: 'true'
ChannelController.java
package com.project.youtube.channel;
import com.project.youtube.channel.dto.body.CreateChannelDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.UUID;
#RestController
#RequestMapping("/api/v1/channels")
public class ChannelController {
#Autowired
ChannelServiceInterface channelService;
#PostMapping
Channel createChannel(#Valid #RequestBody CreateChannelDTO channel){
return channelService.saveChannel(channel);
}
#GetMapping("/findById/{id}")
Channel findById(#PathVariable UUID id){
return channelService.findById(id).orElseThrow();
}
#GetMapping("/findByName/{name}")
Channel findByName(#PathVariable String name){
return channelService.findByName(name).orElseThrow();
}
}
ChannelService.java
package com.project.youtube.channel;
import com.project.youtube.channel.dto.body.CreateChannelDTO;
import com.project.youtube.common.exception.BadRequestException;
import com.project.youtube.user.User;
import com.project.youtube.user.UserServiceInterface;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.UUID;
#Service
public class ChannelService implements ChannelServiceInterface {
#Autowired
ChannelRepository channelRepository;
#Autowired
ModelMapper modelMapper;
#Autowired
UserServiceInterface userService;
#Override
public Page<Channel> findAll(Pageable pageable) {
return null;
}
#Override
public Channel saveChannel(CreateChannelDTO channel) {
Channel channelEntity = modelMapper.map(channel, Channel.class);
User user = userService.findById(channel.getUser()).orElseThrow();
System.out.println(user);
if(user.getChannel() != null){
throw new BadRequestException("User already has a channel");
}
channelEntity.setUser(user);
return channelRepository.save(channelEntity);
}
#Override
public Optional<Channel> findById(UUID id) {
return channelRepository.findById(id);
}
#Override
public Optional<Channel> findByName(String name) {
return channelRepository.findByName(name);
}
}
error
2022-10-22 15:07:20.441 INFO 1 --- [ restartedMain] com.project.youtube.YoutubeApplication : Starting YoutubeApplication v0.0.1-SNAPSHOT using Java 17.0.4.1 on 369da96882ed with PID 1 (/workspace/BOOT-INF/classes started by cnb in /workspace)
2022-10-22 15:07:20.441 INFO 1 --- [ restartedMain] com.project.youtube.YoutubeApplication : The following 1 profile is active: "dev"
2022-10-22 15:07:20.568 INFO 1 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-10-22 15:07:20.577 INFO 1 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8 ms. Found 4 JPA repository interfaces.
2022-10-22 15:07:20.620 INFO 1 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-10-22 15:07:20.621 INFO 1 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-10-22 15:07:20.621 INFO 1 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-10-22 15:07:20.626 INFO 1 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-10-22 15:07:20.626 INFO 1 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 183 ms
2022-10-22 15:07:20.649 WARN 1 --- [ restartedMain] .s.b.d.a.RemoteDevToolsAutoConfiguration : Listening for remote restart updates on /.~~spring-boot!~/restart
2022-10-22 15:07:20.660 INFO 1 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-10-22 15:07:20.662 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Starting...
2022-10-22 15:07:20.670 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Start completed.
2022-10-22 15:07:20.671 INFO 1 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2022-10-22 15:07:20.751 INFO 1 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-10-22 15:07:20.751 INFO 1 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-10-22 15:07:20.756 WARN 1 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.f
actory.UnsatisfiedDependencyException: Error creating bean with name 'channelController': Unsatisfied dependency expressed through field 'channelService'; nested exception is org.springframework.beans.facto
ry.NoSuchBeanDefinitionException: No qualifying bean of type 'com.project.youtube.channel.ChannelServiceInterface' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-10-22 15:07:20.756 INFO 1 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-10-22 15:07:20.757 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Shutdown initiated...
2022-10-22 15:07:20.758 INFO 1 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-5 - Shutdown completed.
2022-10-22 15:07:20.758 INFO 1 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-10-22 15:07:20.764 INFO 1 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-10-22 15:07:20.780 ERROR 1 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field channelService in com.project.youtube.channel.ChannelController required a bean of type 'com.project.youtube.channel.ChannelServiceInterface' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.project.youtube.channel.ChannelServiceInterface' in your configuration.
Native Memory Tracking:
Total: reserved=6967925842, committed=410233938
- Java Heap (reserved=6144655360, committed=155189248)
(mmap: reserved=6144655360, committed=155189248)
- Class (reserved=98438868, committed=12259028)
(classes #16438)
( instance classes #15272, array classes #1166)
(malloc=1969876 #37911)
(mmap: reserved=96468992, committed=10289152)
( Metadata: )
( reserved=67108864, committed=63832064)
( used=63492728)
( waste=339336 =0.53%)
( Class space:)
( reserved=96468992, committed=10289152)
( used=9920144)
( waste=369008 =3.59%)
- Thread (reserved=28445208, committed=1350168)
(thread #28)
(stack: reserved=28364800, committed=1269760)
(malloc=45944 #196)
(arena=34464 #60)
- Code (reserved=255452840, committed=27645608)
(malloc=1820328 #9753)
(mmap: reserved=253632512, committed=25825280)
- GC (reserved=284467544, committed=62202200)
(malloc=22499672 #9236)
(mmap: reserved=261967872, committed=39702528)
- Compiler (reserved=44841728, committed=44841728)
(malloc=47848 #1198)
(arena=44793880 #27)
- JVMCI (reserved=104, committed=104)
(malloc=104 #7)
- Internal (reserved=452902, committed=452902)
(malloc=416038 #11608)
(mmap: reserved=36864, committed=36864)
- Symbol (reserved=16537712, committed=16537712)
(malloc=15678152 #395104)
(arena=859560 #1)
- Native Memory Tracking (reserved=7534776, committed=7534776)
(malloc=7288 #101)
(tracking overhead=7527488)
- Shared class space (reserved=12582912, committed=10981376)
(mmap: reserved=12582912, committed=10981376)
- Arena Chunk (reserved=6492528, committed=6492528)
(malloc=6492528)
- Tracing (reserved=33121, committed=33121)
(malloc=393 #10)
(arena=32728 #1)
If I wanna start my app first I run ./mvnw spring-boot:build-image -fn to create spring boot image and then docker-compose up. It starts perfectly fine, it crashes only when live reload is triggered. Also I have created run configuration in intellij (without it live reload is not working).
So if anyone knows how to deal with it, please help, cause this became very frustrating. I actually do not know what is wrong here. This is the only docker setup, that I able to find, that works with live reload, if someone knows better docker setup, that works with live reload please share with me.
github https://github.com/EivydasV/spring-youtube
I am trying to run a basic spring boot application with JPA by using spanner emulator. However, I am getting the below error after startup after hitting any exposed end point.
PERMISSION_DENIED: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
Project has been cloned from https://github.com/GoogleCloudPlatform/google-cloud-spanner-hibernate/tree/master/google-cloud-spanner-hibernate-samples/spring-data-jpa-sample
and the only change I have done is updated the application.properties file.
as per my understanding spanner emulator should not have any IAM related issues as it doesn't need any. I am not sure what is causing this issue here. I have verified that the emulator config is the active config and hence I would expect the code to connect to emulator.
# Application configuration to use Cloud Spanner with Spring Data JPA
# Spanner connection URL.
# - ${PROJECT_ID} Replace with your GCP project ID
# - ${INSTANCE_ID} Replace with your Spanner instance ID
# - ${DATABASE_NAME} Replace with your Spanner database name within your Spanner instance
spring.datasource.url=jdbc:cloudspanner:/projects/test-project/instances/test-instance/databases/test-database
# Specify the Spanner JDBC driver.
spring.datasource.driver-class-name=com.google.cloud.spanner.jdbc.JdbcDriver
# Specify the Spanner Hibernate dialect.
spring.jpa.properties.hibernate.dialect=com.google.cloud.spanner.hibernate.SpannerDialect
#spring.jpa.hibernate.ddl-auto=update //same error even if I uncomment this line
# Settings to enable batching statements for efficiency
spring.jpa.properties.hibernate.jdbc.batch_size=100
# You may display SQL statements and stats for debugging if needed.
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
Please find the console logs below:
2021-10-06 12:59:12.549 INFO 9747 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-10-06 12:59:12.556 INFO 9747 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-10-06 12:59:12.556 INFO 9747 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.53]
2021-10-06 12:59:12.617 INFO 9747 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-10-06 12:59:12.617 INFO 9747 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 694 ms
2021-10-06 12:59:12.707 INFO 9747 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-10-06 12:59:12.737 WARN 9747 --- [ main] c.g.a.oauth2.DefaultCredentialsProvider : Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts, see https://cloud.google.com/docs/authentication/.
2021-10-06 12:59:14.558 INFO 9747 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (Network timeout is not supported)
2021-10-06 12:59:22.165 INFO 9747 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-10-06 12:59:22.197 INFO 9747 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-06 12:59:22.231 INFO 9747 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.29.Final
2021-10-06 12:59:22.337 INFO 9747 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-06 12:59:22.396 INFO 9747 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: com.google.cloud.spanner.hibernate.SpannerDialect
2021-10-06 12:59:22.851 INFO 9747 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-06 12:59:22.857 INFO 9747 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-06 12:59:23.060 WARN 9747 --- [ 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
2021-10-06 12:59:23.184 INFO 9747 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2021-10-06 12:59:23.290 INFO 9747 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-06 12:59:23.298 INFO 9747 --- [ main] com.example.CoffeeApplication : Started CoffeeApplication in 12.957 seconds (JVM running for 13.227)
2021-10-06 12:59:33.646 INFO 9747 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-10-06 12:59:33.646 INFO 9747 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-10-06 12:59:33.647 INFO 9747 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Hibernate:
select
customer0_.id as id1_1_,
customer0_.email as email2_1_,
customer0_.name as name3_1_
from
customer customer0_
2021-10-06 12:59:35.650 WARN 9747 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 7, SQLState: null
2021-10-06 12:59:35.650 ERROR 9747 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : PERMISSION_DENIED: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
2021-10-06 12:59:35.668 ERROR 9747 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
at io.grpc.Status.asRuntimeException(Status.java:535) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:533) ~[grpc-stub-1.40.1.jar:1.40.1]
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40) ~[grpc-api-1.40.1.jar:1.40.1]
at com.google.cloud.spanner.spi.v1.SpannerErrorInterceptor$1$1.onClose(SpannerErrorInterceptor.java:100) ~[google-cloud-spanner-6.12.5.jar:6.12.5]
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:557) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:69) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:738) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:717) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133) ~[grpc-core-1.40.1.jar:1.40.1]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_281]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_281]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_281]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.8.0_281]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_281]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_281]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_281]
The error is a clear indication that your application is not trying to connect to the emulator, but to a real Spanner database. In order to connect to the emulator instead of 'real' Cloud Spanner, you should do one of the following:
Set the environment variable SPANNER_EMULATOR_HOST=localhost:9010
OR: Edit the JDBC connection URL to include the autoConfigEmulator=true property. Your JDBC URL would then become jdbc:cloudspanner:/projects/test-project/instances/test-instance/databases/test-database;autoConfigEmulator=true
The advantage of the second alternative is that the autoConfigEmulator property will not only ensure that the JDBC driver is connecting to the emulator, it will also automatically create the test-instance and test-database on the emulator if they do not already exist.
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
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
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