How to deploy Spring app in docker container? - java

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

Related

Docker PostgreSQL image

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!

docker image not connecting to mongodb

when I build my docker image and run it it gives this and error however if I run the jar file everything runs fine if I had it guess it would have to do with my docer-compose.yml file but idk
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.2.3.jar!/:na]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:633) ~[na:na]
at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:107) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.2.3.jar!/:na]
... 4 common frames omitted
Dockerfile
FROM openjdk:17
ADD target/docker-document-rest-api.jar docker-document-rest-api.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "docker-document-rest-api.jar"]
application.properties
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=rootuser
spring.data.mongodb.password=rootpass
spring.data.mongodb.database=example
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
docer-compose.yml
version: "3.8"
services:
mongodb:
image: mongo
container_name: mongodb
ports:
- 27017:27017
volumes:
- data:/data
environment:
- MONGO_INITDB_ROOT_USERNAME=rootuser
- MONGO_INITDB_ROOT_PASSWORD=rootpass
mongo-express:
image: mongo-express
container_name: mongo-express
restart: always
ports:
- 8081:8081
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=rootuser
- ME_CONFIG_MONGODB_ADMINPASSWORD=rootpass
- ME_CONFIG_MONGODB_SERVER=mongodb
volumes:
data: {}
networks:
default:
name: mongodb_network
By default docker containers are using bridge networking, so you cannot connect to localhost from a container. There can be several ways to solve this, one would be to connect your container, which is running the Java application, to the network where MongoDB is placed.
Since in your docker-compose you explicitly specify the name of the network (mongodb_network), we can do the following:
In the properties file we have to change localhost to mongodb, so:
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=rootuser
spring.data.mongodb.password=rootpass
spring.data.mongodb.database=example
spring.data.mongodb.port=27017
spring.data.mongodb.host=mongodb
The reason for this is that name of the container can be used as hostname if we connect to the network in which the container is placed.
Rebuild the docker image for the Java application, run it as such:
docker run --network=mongodb_network -p 8080:8080 <docker-image-name>
(fill in your docker image name there)
While these steps might work, I suggest to add the your application to the docker-compose:
version: "3.8"
services:
mongodb:
image: mongo
container_name: mongodb
expose:
- 27017
ports:
- 27017:27017
volumes:
- data:/data
environment:
- MONGO_INITDB_ROOT_USERNAME=rootuser
- MONGO_INITDB_ROOT_PASSWORD=rootpass
mongo-express:
image: mongo-express
container_name: mongo-express
restart: always
ports:
- 8081:8081
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=rootuser
- ME_CONFIG_MONGODB_ADMINPASSWORD=rootpass
- ME_CONFIG_MONGODB_SERVER=mongodb
spring_application:
build: .
container_name: spring_application
ports:
- 8080:8080
depends_on:
mongodb:
condition: service_started
volumes:
data: {}
networks:
default:
name: mongodb_network
This has to be build first with docker-compose build and afterwards can be executed with docker-compose up.
You must use docker internal host network to connect with mongodb. So from your dockerized application you have to connect with the service name (as that is the hostname) instead of connecting with localhost. In your case: http://mongodb:27017 is the service (and thus hostname) of your mongo db container.

Docker container crashes at startup on a remote server, how to run correctly?

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.

EurekaServer com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server on Docker

Eureka server not working on Docker compose
Here is the docker-compose for the Eureka server and config server
version: '3'
services:
fetebird-eurekaservice:
container_name: FeteBird-EurekaService
build:
context: ../../Eureka-Service-Registry/
dockerfile: Dockerfile
image: fetebird/eurekaservice
ports:
- "8761:8761"
networks:
- spring-cloud-network
volumes:
- ./fetebird-eurekaservice/data:/data
logging:
driver: json-file
fetebird-configserver:
container_name: FeteBird-ConfigServer
build:
context: ../../FeteBird-ConfigServer
dockerfile: Dockerfile
image: fetebird/configserver
ports:
- "8085:8085"
networks:
- spring-cloud-network
volumes:
- ./fetebird-configserver/data:/data
logging:
driver: json-file
networks:
spring-cloud-network:
driver: bridge
I tried with the expose command as well but no luck
Eureka server docker file
FROM openjdk:14
WORKDIR /fetebird-eurekaservice/service
ADD build/libs/fete-bird-eureka-service-registry-0.0.1-SNAPSHOT.jar fete-bird-eureka-service-registry-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java", "-jar", "fete-bird-eureka-service-registry-0.0.1-SNAPSHOT.jar"]
Config server Client Docker file
FROM openjdk:14
WORKDIR /fetebird-eurekaservice/service
ADD build/libs/fete-bird-configuration-server-0.0.1-SNAPSHOT.jar fete-bird-configuration-server-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java", "-jar", "fete-bird-configuration-server-0.0.1-SNAPSHOT.jar"]
Config Server
#SpringBootApplication
#EnableEurekaServer
public class FeteBirdEurekaServiceRegistryApplication {
public static void main(String[] args) {
SpringApplication.run(FeteBirdEurekaServiceRegistryApplication.class, args);
}
}
Configuration of Eureka server
application.yml
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
spring:
profiles:
active: dev
bootstrap.yml
spring:
application:
name: CONFIG-SERVER
profiles:
active: native
cloud:
config:
server:
native:
search-locations: classpath:/config
Config Server
server:
port: 8085
Discovery Server Access
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
hostname: localhost
Errors
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
FeteBird-ConfigServer | at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:112) ~[eureka-client-1.9.21.jar!/:1.9.21]
FeteBird-ConfigServer | at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.register(EurekaHttpClientDecorator.java:56) ~[eureka-client-1.9.21.jar!/:1.9.21]
FeteBird-ConfigServer | at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$1.execute(EurekaHttpClientDecorator.java:59) ~[eureka-client-1.9.21.jar!/:1.9.21]
FeteBird-ConfigServer | at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77) ~[eureka-client-1.9.21.jar!/:1.9.21]
FeteBird-ConfigServer | at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.register(EurekaHttpClientDecorator.java:56) ~[eureka-client-1.9.21.jar!/:1.9.21]
FeteBird-ConfigServer | at com.netflix.discovery.DiscoveryClient.register(DiscoveryClient.java:857) ~[eureka-client-1.9.21.jar!/:1.9.21]
FeteBird-ConfigServer | at com.netflix.discovery.InstanceInfoReplicator.run(InstanceInfoReplicator.java:121) ~[eureka-client-1.9.21.jar!/:1.9.21]
FeteBird-ConfigServer | at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
FeteBird-ConfigServer | at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
FeteBird-ConfigServer | at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]
FeteBird-ConfigServer | at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
FeteBird-ConfigServer | at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
FeteBird-ConfigServer | at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
FeteBird-ConfigServer |
FeteBird-ConfigServer | 2020-07-20 14:30:19.268 WARN 1 --- [nfoReplicator-0] c.n.discovery.InstanceInfoReplicator : There was a problem with the instance info replicator
The problem is this
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1111/eureka
It is pointing to localhost and Eureka is no longer running on localhost, localhost in this case is the individual containers. The containers are linked together so you can just change this to
eureka:
client:
serviceUrl:
defaultZone: http://fetebird-eurekaservice:8761/eureka/
instance:
hostname: fetebird-eurekaservice
Each docker file
ENTRYPOINT ["java", "-jar", "fete-bird-configuration-server-0.0.1-SNAPSHOT.jar"] fetebird-eurekaservice
Docker compose file (Add links and depends_on)
fetebird-configserver:
container_name: FeteBird-ConfigServer
build:
context: ../../FeteBird-ConfigServer
dockerfile: Dockerfile
image: fetebird/configserver
ports:
- "8085:8085"
links:
- fetebird-eurekaservice
depends_on:
- fetebird-eurekaservice
networks:
- spring-cloud-network
volumes:
- ./fetebird-configserver/data:/data
logging:
driver: json-file
Reference - https://github.com/spring-cloud/spring-cloud-netflix/issues/2442
As pointed out by OP's answer: Eureka is no longer running on localhost, localhost in this case is the individual containers.
I'm here to introduce two addtional solutions:
Solution 1. Using docker environment
Dev environment (in application.properties):
eureka.client.service-url.defaultZone = http://localhost:8761/eureka
Docker environment (override defaultZone settings in docker-compose.yml file):
myservice:
container_name: myservice
environment:
eureka.client.service-url.defaultZone: http://<your-eureka-service-name>:8761/eureka
This will override application.properties or application.yml values.
If you'd like to override a bunch stuff in docker environment like jdbc connection, you can use SPRING_APPLICATION_JSON (spring will read it as it is embedded in an environment variable or system property):
myservice:
container_name: myservice
environment:
SPRING_APPLICATION_JSON: '{
"spring.datasource.url=jdbc:mysql": "//jdbc:mysql:3306/mydb",
"spring.datasource.username": "username",
"spring.datasource.password": "password",
"spring.jpa.hibernate.ddl-auto": "update",
"eureka.client.service-url.defaultZone": "http://<your-eureka-service-name>:8761/eureka"
}'
Solution 2. Setting up different profiles:
Step one, prepare two versions of application.properties, if you prefer application.yml, your choise:
application-default.properties for dev environment:
eureka.client.service-url.defaultZone = http://localhost:8761/eureka
application-docker.properties for docker environment:
eureka.client.service-url.defaultZone = http://<your-eureka-service-name>:8761/eureka
Step two (docker-compose file):
myservice:
container_name: myservice
environment:
SPRING_PROFILES_ACTIVE: docker
By setting up SPRING_PROFILES_ACTIVE to docker, it will load application-docker.properties as active profiles.
References:
Spring Profiles
Spring Environment-Specific Properties File
How to load the SPRING_PROFILES_ACTIVE value in the client service dynamically?

docker compose can not connect to postgresql

application.properties
spring.datasource.url=jdbc:postgresql://db:5432/test
spring.datasource.username=postgres
spring.datasource.password=123
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.id.new_generator_mappings=true
server.port=8000
docker-compose
version: '3.7'
services:
db:
image: postgres:11.4
ports:
- "5432:5432"
expose:
- 5432
environment:
POSTGRES_PASSWORD: "root"
POSTGRES_DB: test
lady:
depends_on:
- db
build: ./test/
ports:
- "8000:8000"
expose:
- 8000
environment:
DB_USER: "postgres"
DB_PASSWORD: "123"
DB_TYPE: "postgres"
command: ["java","-jar","test.jar"]
logs error
com.women.lady.LadyApplicationTests > contextLoads() FAILED
java.lang.IllegalStateException
Caused by: org.springframework.beans.factory.BeanCreationException
Caused by: javax.persistence.PersistenceException
Caused by: org.hibernate.exception.JDBCConnectionException
Caused by: org.postgresql.util.PSQLException
Caused by: java.net.UnknownHostException
I can't connect to postgres or db when I run docker compose: docker-compose up
Question
How to connect db on docker-compose.
Please give me example.

Categories