i'm new to Docker and have been trying to Dockerize a simple springboot and MySQL project.
I have created an image for spring boot and also have a container for my springboot project and a separate container for MySQL.
When I attempt to log the container logs for the MySQL part it works with no errors.
docker container logs mysql-standalone
2021-12-20T18:27:56.109823Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2021-12-20T18:27:56.184989Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2021-12-20T18:27:56.375549Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2021-12-20T18:27:56.376015Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.27' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
But, when I try to log for the Springboot project I get an error
**docker container logs springboot-docker **
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.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.6.1.Final.jar!/:5.6.1.Final]
My current containers
When I attempt to run the project locally with an IDE it works perfectly, the endpoints work fine with no errors.
I'm not too sure where the problem lies, if anyone has some ideas please let me know.
New Error
java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-java-8.0.27.jar!/:8.0.27]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na]
application.properties (Database config)
spring.datasource.url=jdbc:mysql://mysql-standalone:3306/docker_demo?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
Update 01: Updated cmd, written here for code block
docker run --name mysql-standalone -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=docker-demo -e MYSQL_USER=demo -e MYSQL_PASSWORD=password -d mysql:8.0.27
Short answer: you need to run the docker container with the port specified like so:
docker run -it -p 3306:3306 mysql
Then you should be able to connect :)
If you share your docker file or docker-compose, i will be happy to assist with the command.
Longer answer is that you need to bind the container port to your host machines network in order for non-dockerized services to be able to access the port on the container. This is very usefull when having to run multiple mysql containers on the same machine, then you just bind to a different host port and everything should be good to go :)
Related
I cannot connect to postgresql from intellij idea while running app. It failes to connect to all kinds of datababes - to local db, remote dbs and so on. But it can easily connect these dbs using dbeaver and the app works perfectly on server. Also, the connection is okay if I use another machine for this. Do anyone know, how to fix it? Here is the stacktrace from intellij:
Caused by: org.postgresql.util.PSQLException: ERROR: Auth failed
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:659) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:180) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:235) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:247) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.Driver.makeConnection(Driver.java:434) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.Driver.connect(Driver.java:291) ~[postgresql-42.5.1.jar:42.5.1]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar:na]
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:266) ~[liquibase-core-4.8.0.jar:na]
I tried everything but nothing helped
I am trying to create a postgresql image using docker for my db. For some reason it doesn't create my new Database or anything.
When I try to run my container I receive this:
2022-09-04T18:07:11.604283300Z ***************************
2022-09-04T18:07:11.604288900Z APPLICATION FAILED TO START
2022-09-04T18:07:11.604293000Z ***************************
2022-09-04T18:07:11.604297200Z
2022-09-04T18:07:11.604301200Z Description:
2022-09-04T18:07:11.604305400Z
2022-09-04T18:07:11.604309400Z Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
2022-09-04T18:07:11.604313700Z
2022-09-04T18:07:11.604317400Z Reason: Failed to determine a suitable driver class
2022-09-04T18:07:11.604322700Z
2022-09-04T18:07:11.604326800Z
2022-09-04T18:07:11.604346700Z Action:
2022-09-04T18:07:11.604351000Z
2022-09-04T18:07:11.604355000Z Consider the following:
2022-09-04T18:07:11.604359200Z If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
2022-09-04T18:07:11.604363500Z If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).```
but my application properties looks like this:
server.port=8091
#liquibase properties
spring.liquibase.enabled=true
spring.liquibase.change-log=db/changelog/db.changelog-root.xml
spring.liquibase.defaultSchema=activities_schema
spring.datasource.url=jdbc:postgresql://localhost:5432/random-activities-db
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.show-sql=true
I am trying to do this in a SpringBoot application.
Also:
Dockerfile:
FROM openjdk:latest
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} application.jar
ENTRYPOINT ["java", "-jar", "application.jar"]
docker-compose:
services:
db:
image: postgres
restart: always
environment:
- POSTGRES_DB=random-activities-db
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=admin
ports:
- 5432:5432
volumes:
- ./src/main/resources/db/init.sql:/docker-entrypoint-initdb.d/init.sql
Later edit:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-09-04T18:51:23.450200700Z 2022-09-04 18:51:23.449 ERROR 1 --- [ main] o.s.boot.SpringApplication : Application run failed
2022-09-04T18:51:23.450267900Z
2022-09-04T18:51:23.450280700Z org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.DatabaseException: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
2022-09-04T18:51:23.450287700Z at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450292500Z at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450296500Z at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450300700Z at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450305200Z at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450309600Z at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450314400Z at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450318600Z at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450324800Z at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450330000Z at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450334400Z at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450351200Z at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450357000Z at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.3.jar!/:2.7.3]
2022-09-04T18:51:23.450361800Z at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.3.jar!/:2.7.3]
2022-09-04T18:51:23.450366100Z at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.3.jar!/:2.7.3]
2022-09-04T18:51:23.450371100Z at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.3.jar!/:2.7.3]
2022-09-04T18:51:23.450375400Z at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.3.jar!/:2.7.3]
2022-09-04T18:51:23.450379500Z at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.3.jar!/:2.7.3]
2022-09-04T18:51:23.450383500Z at com.John.random_activity.RandomActivityApplication.main(RandomActivityApplication.java:10) ~[classes!/:0.0.1-SNAPSHOT]
2022-09-04T18:51:23.450387300Z at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
2022-09-04T18:51:23.450391400Z at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
2022-09-04T18:51:23.450395800Z at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[application.jar:0.0.1-SNAPSHOT]
2022-09-04T18:51:23.450400000Z at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[application.jar:0.0.1-SNAPSHOT]
2022-09-04T18:51:23.450403900Z at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[application.jar:0.0.1-SNAPSHOT]
2022-09-04T18:51:23.450408200Z at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65) ~[application.jar:0.0.1-SNAPSHOT]
2022-09-04T18:51:23.450411300Z Caused by: liquibase.exception.DatabaseException: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
2022-09-04T18:51:23.450414900Z at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:271) ~[liquibase-core-4.9.1.jar!/:na]
2022-09-04T18:51:23.450418300Z at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450421700Z at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.22.jar!/:5.3.22]
2022-09-04T18:51:23.450425300Z ... 24 common frames omitted
2022-09-04T18:51:23.450428600Z Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
2022-09-04T18:51:23.450437400Z at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:319) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450443100Z at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450459300Z at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:223) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450463600Z at org.postgresql.Driver.makeConnection(Driver.java:402) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450467200Z at org.postgresql.Driver.connect(Driver.java:261) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450470600Z at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
2022-09-04T18:51:23.450474300Z at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
2022-09-04T18:51:23.450477700Z at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
2022-09-04T18:51:23.450480700Z at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na]
2022-09-04T18:51:23.450483700Z at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na]
2022-09-04T18:51:23.450488100Z at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na]
2022-09-04T18:51:23.450491900Z at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na]
2022-09-04T18:51:23.450495600Z at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:266) ~[liquibase-core-4.9.1.jar!/:na]
2022-09-04T18:51:23.450499100Z ... 26 common frames omitted
2022-09-04T18:51:23.450503000Z Caused by: java.net.ConnectException: Connection refused
2022-09-04T18:51:23.450507000Z at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
2022-09-04T18:51:23.450510500Z at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
2022-09-04T18:51:23.450514100Z at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:539) ~[na:na]
2022-09-04T18:51:23.450517900Z at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:594) ~[na:na]
2022-09-04T18:51:23.450521600Z at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327) ~[na:na]
2022-09-04T18:51:23.450525700Z at java.base/java.net.Socket.connect(Socket.java:633) ~[na:na]
2022-09-04T18:51:23.450529300Z at org.postgresql.core.PGStream.createSocket(PGStream.java:241) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450533000Z at org.postgresql.core.PGStream.<init>(PGStream.java:98) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450537100Z at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:109) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450559100Z at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:235) ~[postgresql-42.3.6.jar!/:42.3.6]
2022-09-04T18:51:23.450563800Z ... 38 common frames omitted
2022-09-04T18:51:23.450568100Z
Now it starts but I receive this. I verified if the port is open: is open and listening on postgres.
The problem in your infrastructure is the link between the db service and the spring service.
By default, when running containers, each one has its "proper network". It means that the container is not reachable from outside (except exposed ports) and not reachable from other containers. That means, in the current context, your spring container and your database container cannot communicate between each other
Hopefully, there is a solution to link your containers to make them interact with each others => Docker Networks (see this page for more informations about them). Docker-compose can manage these networks and links for you very simply by providing the links array in your docker-compose.yml
Have a look at the docker-compose documentation on networking!
Your docker-compose.yml should now look like this:
version: "3.0"
services:
spring:
build: . # Or image: yourimage:version
restart: always
links: # Specify the links with another containers
- db # Make the db container reachable from this container through hostname "db"
ports:
- 8091:8091
db:
image: postgres
restart: always
environment:
- POSTGRES_DB=random-activities-db
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=admin
ports:
- 5432:5432
volumes:
- ./src/main/resources/db/init.sql:/docker-entrypoint-initdb.d/init.sql
Now that your docker-compose.yml is properly configured, you can access the database container from the db hostname in your spring container. That means you have to change your application.properties from this:
spring.datasource.url=jdbc:postgresql://localhost:5432/random-activities-db
to this:
spring.datasource.url=jdbc:postgresql://db:5432/random-activities-db
Also, I suggest you to use environment variables (placeholders in Spring) to specify database-related stuff:
spring.datasource.url=jdbc:postgresql://${DB_HOST}/${DB_NAME}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
Your docker-compose spring container configuration should now look like this:
services:
spring:
build: . # Or image: yourimage:version
restart: always
links: # Specify the links with another containers
- db # Make the db container reachable from this container through hostname "db"
environment: # System environment reachable via ${KEY} in Spring
- "DB_HOST=db:5432"
- DB_NAME=random-activities-db
- DB_USER=postgres
- DB_PASSWORD=admin
ports:
- 8091:8091
And that's it!
I have the Spring Boot app and the following Dockerfile:
FROM openjdk:16
COPY build/libs/*.jar tg-bot.jar
ENTRYPOINT java -Dfile.encoding=UTF-8 -jar tg-bot.jar
EXPOSE 8080
The application runs correctly in Docker on my PC:
docker run -p 8080:8080 tg-bot
Then I pushed image to my Dockerhub repository, pull it in Docker on my VPS and tried to run it with the same command:
docker run -p 8080:8080 tg-bot
When the Spring Boot app starts, an error occurs connecting to the PostgreSQL database:
Caused by: org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:315) ~[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]
at org.springframework.jdbc.datasource.SimpleDriverDataSource.getConnectionFromDriver(SimpleDriverDataSource.java:144) ~[spring-jdbc-5.3.9.jar!/:5.3.9]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205) ~[spring-jdbc-5.3.9.jar!/:5.3.9]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169) ~[spring-jdbc-5.3.9.jar!/:5.3.9]
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:272) ~[liquibase-core-4.3.5.jar!/:na]
... 26 common frames omitted
Caused by: java.net.NoRouteToHostException: No route to host
at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:669) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:645) ~[na:na]
at org.postgresql.core.PGStream.createSocket(PGStream.java:231) ~[postgresql-42.2.23.jar!/:42.2.23]
at org.postgresql.core.PGStream.<init>(PGStream.java:95) ~[postgresql-42.2.23.jar!/:42.2.23]
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:98) ~[postgresql-42.2.23.jar!/:42.2.23]
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213) ~[postgresql-42.2.23.jar!/:42.2.23]
... 34 common frames omitted
This is my application.yml with db settings:
spring:
application:
name: tg-bot
r2dbc:
url: r2dbc:postgresql://postgresql.j5321585.myjino.ru:5432/j5321585_tg_db
username: ********
password: ********
liquibase:
enabled: true
change-log: classpath:db/scripts/changelog-master.xml
url: jdbc:postgresql://postgresql.j5321585.myjino.ru:5432/j5321585_tg_db
user: ********
password: ********
There are no errors when starting the container locally with the same application.yaml. What could be the problem?
This depends on how you are running your Postgres Application.
If Postgres is running on a separate server make sure that server is accessible from within your Application Docker container.
If Postgres is running as a Docker container on same server, you can start both your application and Postgres Docker container as a docker-compose file. In that you can specify the host or ip-address for the Postgres docker container and use the same in your application code.
Hope this is helpful.
I have a problem with Docker-compose. On my machine, I have a Ubuntu. And, when I deploy my app into container, I see that exception:
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:307) ~[liquibase-core-3.6.3.jar!/:na]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.6.RELEASE.jar!/:5.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.6.RELEASE.jar!/:5.1.6.RELEASE]
... 26 common frames omitted
Caused by: org.postgresql.util.PSQLException: Connection to 0.0.0.0: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:280) ~[postgresql-42.2.5.jar!/:42.2.5]
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.5.jar!/:42.2.5]
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195) ~[postgresql-42.2.5.jar!/:42.2.5]
at org.postgresql.Driver.makeConnection(Driver.java:454) ~[postgresql-42.2.5.jar!/:42.2.5]
at org.postgresql.Driver.connect(Driver.java:256) ~[postgresql-42.2.5.jar!/:42.2.5]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:136) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.2.0.jar!/:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.2.0.jar!/:na]
at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:302) ~[liquibase-core-3.6.3.jar!/:na]
... 28 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:240) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:591) ~[na:na]
at org.postgresql.core.PGStream.<init>(PGStream.java:70) ~[postgresql-42.2.5.jar!/:42.2.5]
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:91) ~[postgresql-42.2.5.jar!/:42.2.5]
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:192) ~[postgresql-42.2.5.jar!/:42.2.5]
... 40 common frames omitted
I have configuration of PostgreSQL:
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
host all all 100.200.300.50/32 trust
And that option set "listen_addresses = 'localhost'";
Docker-compose config:
version: '3'
services:
web:
service
image: webserviceimage
ports:
- 8080:8080
depends_on:
- db
- redis
environment:
POSTGRES_URL:
POSTGRES_USER:
POSTGRES_PASSWORD:
redis:
image: "redis:alpine"
restart: unless-stopped
environment:
REDIS_URL: redis:6379
db:
image: postgres
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD:
POSTGRES_USER:
How I can resolve it?
Step: 1 Create Dockerfile
FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
Step:2 Run command to create docker file
docker build -t webapp:latest -f Dockerfile .
Step:3 Add docker image into docker-compose
version: '3'
services:
web:
service
image: webapp:latest
ports:
- 8080:8080
depends_on:
- db
- redis
environment:
POSTGRES_URL:
POSTGRES_USER:
POSTGRES_PASSWORD:
redis:
image: "redis:alpine"
restart: unless-stopped
environment:
REDIS_URL: redis:6379
db:
image: postgres
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD:
POSTGRES_USER:
Notes : web app environment variable user into application.properties file like
spring.datasource.url = ${POSTGRES_URL}:${POSTGRES_PORT}/"nameofDB"
Make sure you have Postgres configured to listen on all available IP addresses. The configuration file postgresql.conf (typically located in /var/lib/postgresql/data/postgresql.conf) must have:
listen_addresses = '*'
(this is the default configuration). More here
The file pg_hba.conf contains the configuration for the host based authentication. The posted configuration means that connections coming from the IPs with the defined mask or unix sockets are trusted (don't require authentication). You don't have to change this file unless you have specific security requirements. By default remote clients must supply an MD5-encrypted password for authentication:
host all all all md5
For more info see The pg_hba.conf File
What was suggested in the comments is to change the URL of the database in the configuration of the spring boot application. From the logs the application tries to connect to 0.0.0.0 which is not a valid outbound address (see here).
Change the URL in the application properties to something like this:
spring.datasource.url=jdbc:postgresql://db:5432/<database_name>
spring.datasource.username=<database_user>
spring.datasource.password=<password>
db is the name of the database container which can be resolved by the service container to the correct database IP address.
Hope it helps
I have been trying to host a web application on AWS EC2 Ubuntu t1.micro instance.
MySQL version: 5.5.35
Tomcat version: 7.0.52
JDK version: 7.0_51
The context for the webapp is:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/XYZ" docBase="XYZ"
debug="5" reloadable="true" crossContext="true">
<Resource name="jdbc/XYZ" auth="Container" type="javax.sql.DataSource"
factory="org.apache.commons.dbcp.BasicDataSourceFactory"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/XYZ?characterEncoding=UTF-8"
username="root" maxActive="100" maxIdle="50" removeAbandoned="true"
useUnicode="true" autoReconnect="true"
removeAbandonedTimeout="60" logAbandoned="true"
password="root"/>
</Context>
The error that gets thrown when i start tomcat is as follows
AbandonedObjectPool is used (org.apache.commons.dbcp.AbandonedObjectPool#3f445d30)
LogAbandoned: true
RemoveAbandoned: true
RemoveAbandonedTimeout: 60
WARN [localhost-startStop-1] (JDBCExceptionReporter.java:71) - SQL Error: 0, SQLState: null
ERROR [localhost-startStop-1] (JDBCExceptionReporter.java:72) - Cannot create PoolableConnectionFactory (Unknown database 'XYZ')
WARN [localhost-startStop-1] (SettingsFactory.java:103) - Could not obtain connection metadata
org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Unknown database 'XYZ')
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:855)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:540)
at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:72)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:805)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:745)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1167)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:427)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:249)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:155)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:246)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:285)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:245)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:188)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4973)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'XYZ'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:37)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:290)
at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:877)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:851)
... 33 more
My AWS security groups are set as follows
Type Protocol PortRange Source
MYSQL TCP 3306 127.0.0.1/32
SSH TCP 22 0.0.0.0/0
HTTP TCP 22 0.0.0.0/0
HTTPS TCP 22 0.0.0.0/0
All traffic TCP 22 0.0.0.0/0
I checked the host that MySQL is running on
$ netstat -tln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp6 0 0 :::22 :::* LISTEN
If I try connecting to MySQL using
mysql -u root -h 127.0.0.1 -D database_name -p
the connection works just fine.
Everything seems to be ok. Still I cant seem to find the reason the error is being thrown.
Would really appreciate some expert advice.
Thanks in advance.
Found the solution.
The reason I was getting the error is due to Linux version of MySQL being case sensitive to the database name. When I moved my entire stack from Windows to Linux I faced this problem.
Windows MySQL database names are not case-sensitive and Linux MySQL database names are case-sensitive.
Below rule is redundant. So remove it.
MYSQL TCP 3306 127.0.0.1/32
Your MySQL is listening on only localhost:
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
This is not a problem as long as you are connecting to MySQL locally. But any remote connection to MySQl will fails. If this is the case, then change the MySQL binding to 0.0.0.0 in my.cnf.
Before running you code, could you try connecting to the MySQL locally using the MySQL cli as below:
mysql -u <username> -h 127.0.0.1 -p
If this connection works fine, then check whether you are able to connect fine with your jdbc driver. Also, double check your jdbc settings.