docker-compse.yml spring boot mysql configuration [duplicate] - mysql

This question already has an answer here:
Configuring Spring boot Docker and Mysql
(1 answer)
Closed 3 years ago.
I have been trying to configure docker for my spring boot application with MySQL. But, I keep getting communications link failure error after running
docker compose up
Here's a snapshot of the error
spring-batch_1 | 2019-11-14 06:23:43.713 INFO 1 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
spring-batch_1 | 2019-11-14 06:23:43.918 ERROR 1 --- [ main]
com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool
initialization.
spring-batch_1 |
spring-batch_1 | com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link
failure
spring-batch_1 |
spring-batch_1 | The last packet sent successfully to the server was 0 milliseconds ago. The
driver has not received any packets from the server.
spring-batch_1 | at
com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[ .
mysql-connector-java-8.0.18.jar!/:8.0.18]
spring-batch_1 | at
com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException
(SQLExceptionsMapping.java:64 ) ~[mysql-connector-java-8.0.18.jar!/:8.0.18]
spring-batch_1 | at
com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-
8.0.18.jar!/:8.0.18]
spring-batch_1 | at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~
[mysql-connector-java-8.0.18.jar!/:8.0.18]
spring-batch_1 | at
com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-
8.0.18.jar!/:8.0.18]
spring-batch_1 | at
com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-
connector-java-8.0.18.jar!/:8.0.18]
spring-batch_1 | at
com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-
3.4.1.jar!/:na]
spring-batch_1 | at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:353) ~
[HikariCP-3.4.1.jar!/:na]
spring-batch_1 | at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201) ~
[HikariCP-3.4.1.jar!/:na]
spring-batch_1 | at
com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) ~[HikariCP-
3.4.1.jar!/:na]
spring-batch_1 | at
com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:562) ~[HikariCP-
3.4.1.jar!/:na]
spring-batch_1 | at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~ .
[HikariCP-3.4.1.jar!/:na]
spring-batch_1 | at
com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-
3.4.1.jar!/:na]
spring-batch_1 | at
com.zaxxer.hikari.HikariDataSource$$FastClassBySpringCGLIB$$eeb1ae86.invoke(<generated>) ~ .
[HikariCP-3.4.1.jar!/:na]
spring-batch_1 | at
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-
5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
spring-batch_1 | at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint
(CglibAopProxy.java:769) ~[spring-aop-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
spring-batch_1 | at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed
(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
spring-batch_1 | at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed
(CglibAopProxy.java:747) ~[spring-aop-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
spring-batch_1 | at
org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed
(DelegatingIntroductionInterceptor.java:136) ~[spring-aop-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
Here's my docker-compose.yml file
version: "3.3"
services:
mysql:
restart: always
image: mysql:latest
ports:
- 6033:3306
expose:
- 6033
volumes:
- db_data:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=root#123
- MYSQL_DATABASE=micro_services
- MYSQL_USER=root
- MYSQL_PASSWORD=root#123
spring-batch:
restart: always
image: ioesandeep/product-service:0.0.1-SNAPSHOT
ports:
- "8082:8082"
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://127.0.0.1:6033/micro_services
SPRING_DATASOURCE_USERNAME: root
SPRING_DATASOURCE_PASSWORD: root#123
SPRING_JPA_DATABASE: mysql
depends_on:
- mysql
volumes:
db_data: {}
and here's my dockerfile which is used to build my spring-batch image
FROM openjdk:11-jdk
VOLUME /tmp
ARG JAR_FILE
ADD ${JAR_FILE} product.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/product.jar"]
I am using dockerfile-maven-plugin from com.spotify to build the image.
Here's my application.properties file for the spring boot and hibernate
spring.application.name=product
server.port=8082
spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.url=jdbc:mysql://127.0.0.1:6033/micro_services
spring.datasource.username=root
spring.datasource.password=root#123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database=mysql
spring.batch.initialize-schema=always
spring.batch.job.enabled=false
Docker version 18.09.2, build 6247962
mysql Ver 8.0.18 for macos10.14 on x86_64 (MySQL Community Server - GPL)
Images
mysql latest c8ee894bd2bd 4 weeks ago
openjdk 11-jdk a7e47afa852b 3 weeks ago
I have tried a lot many configurations for the docker-compose file but every time I get the same error. I am not sure what am I missing in the configuration. I have been trying to get this up for over 2 days now. I would really appreciate a quick help.
Thanks

You have your SPRING_DATASOURCE_URL as localhost (127.0.0.1):
SPRING_DATASOURCE_URL: jdbc:mysql://127.0.0.1:6033/micro_services
Which as far as your spring-batch container is concerned is itself NOT the host machine so it will not be able to connect.
You will need to change it to reference the mysql container like:
SPRING_DATASOURCE_URL: jdbc:mysql://mysql:6033/micro_services

Related

Docker compose service not connecting to mysql container

I am trying to connect my service to MySQL docker container via docker-compose. The connection is refused. I tried to run MySQL docker image and connect my running service to it locally. the connection is established and everything is working fine. The problem is when I want to run both the service and MySQL container, the connection is refused. I created the custom network and tried many solutions but it has already taken me 2 days!
the docker compose configs are:
version : '3.8'
services:
healthcare:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
depends_on:
- mysql
restart: always
environment:
RDS_URL: mysql
networks:
- saman-network
mysql:
image: mysql:8-oracle
container_name:
mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: hospital_db
MYSQL_USER: saman
MYSQL_PASSWORD: saman
volumes:
- myvolume:/var/lib/mysql
ports:
- "3308:3306"
networks:
- saman-network
volumes:
myvolume:
networks:
saman-network:
the application.properties configs are:
server.port=8080
spring.application.name=healthcare
spring.datasource.url=jdbc:mysql://${RDS_URL:localhost}:3308/hospital_db
spring.datasource.username=saman
spring.datasource.password=saman
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
the error I am getting:
springboot-hospitalmng-sample-healthcare-1 | ... 46 common frames omitted
springboot-hospitalmng-sample-healthcare-1 | Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
and
springboot-hospitalmng-sample-healthcare-1 | ... 59 common frames omitted
springboot-hospitalmng-sample-healthcare-1 | Caused by: java.net.ConnectException: Connection refused
springboot-hospitalmng-sample-healthcare-1 | at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
springboot-hospitalmng-sample-healthcare-1 | at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
springboot-hospitalmng-sample-healthcare-1 | at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:an]
springboot-hospitalmng-sample-healthcare-1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
springboot-hospitalmng-sample-healthcare-1 | 2023-01-05T14:20:37.165Z ERROR 1 --- [ main] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
I think this is the problem. mysql runs on port 3306, you expose it on the host on 3308. But from the configuration you connect through the docker network using RDS_URL but port 3308, it should be 3306 instead

Scala app in docker compose - cannot connect to mysql

I have seen multiple other questions on similar topics, but none of them provides a solution that solves my problem. I have, to the best of my ability, checked to make sure that I have tried solutions provided in other similar questions, but none of them appear to work (or I am reading them incorrectly).
I have a small Scala-app to ingest data to a MySQL database. Having both the app and the DB locally, everything works fine. When trying to run using docker compose, I can't connect to the database.
Setup:
Docker compose file:
version: '1'
services:
ingester:
restart: always
build:
context: ./data_ingester
dockerfile: Dockerfile
container_name: data_ingester
links:
- database
depends_on:
- database
grafana:
restart: always
image: grafana/grafana
container_name: grafana_display
volumes:
- ./grafana_display/grafana-storage:/var/lib/grafana
ports:
- 3000:3000
links:
- database
depends_on:
- database
database:
restart: always
image: mysql:5.7
container_name: database
ports:
- 3306:3306
volumes:
- ./mysql_db_setup/db_setup.sql:/docker-entrypoint-initdb.d/db_setup.sql
environment:
MYSQL_ROOT_PASSWORD: pwd
MYSQL_DATABASE: db
MYSQL_USER: mysql_user
MYSQL_PASSWORD: mysql_pw
volumes:
ingester:
grafana:
database:
Starting all this using docker-compose, I am then able to use docker exec to get a bash shell in the database-container and add some sample data to a table.
Following that, I go to the web-ui exposed by the grafana-container and set up a MySQL datasource by specifying host:port as "database:3306" (i.e. the name of the database-container as host with the appropriate port).
This works, I can connect to the MySQL db from the grafana-container and visualise the sample data I inserted, so the database seems reachable and all that.
In my Scala program, which is run using sbt in the ingester-container, I am now setting up a connection as follows:
Class.forName("com.mysql.jdbc.Driver")
ConnectionPool.singleton(
"jdbc:mysql://database:3306?characterEncoding=UTF-8",
"mysql_user",
"mysql_pw"
)
Reading all the other similar questions, I figured this is the right way. Given that I can reach the database from the grafana-container when specifying the connection in this way also makes me believe this is how it should be specified. However, when trying to run this, the scala-program dies with the following error:
data_ingester | [info] welcome to sbt 1.6.1 (Oracle Corporation Java 11.0.14)
data_ingester | [info] loading project definition from /DataIngester/project
data_ingester | [info] loading settings for project dataingester from build.sbt ...
data_ingester | [info] set current project to DataIngester (in build file:/DataIngester/)
data_ingester | [info] running Main
data_ingester | 22:57:35.987 [sbt-bg-threads-1] DEBUG scalikejdbc.ConnectionPool$ - Registered connection pool : ConnectionPool(url:jdbc:mysql://database:3306?characterEncoding=UTF-8, user:mysql_user) using factory : <default>
data_ingester | 22:57:35.993 [sbt-bg-threads-1] DEBUG scalikejdbc.ConnectionPool$ - Registered singleton connection pool : ConnectionPool(url:jdbc:mysql://database:3306?characterEncoding=UTF-8, user:mysql_user)
data_ingester | [error] java.net.ConnectException: Connection refused (Connection refused)
data_ingester | [error] at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
data_ingester | [error] at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412)
data_ingester | [error] at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255)
data_ingester | [error] at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237)
data_ingester | [error] at java.base/java.net.Socket.connect(Socket.java:609)
data_ingester | [error] at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:177)
data_ingester | [error] at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
data_ingester | [error] at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
data_ingester | [error] at java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
data_ingester | [error] at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:341)
data_ingester | [error] at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:362)
data_ingester | [error] at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1253)
data_ingester | [error] at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1187)
data_ingester | [error] at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1081)
data_ingester | [error] at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1015)
data_ingester | [error] at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1592)
data_ingester | [error] at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
data_ingester | [error] at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527)
data_ingester | [error] at scalaj.http.HttpRequest.doConnection(Http.scala:367)
data_ingester | [error] at scalaj.http.HttpRequest.exec(Http.scala:343)
data_ingester | [error] at scalaj.http.HttpRequest.asString(Http.scala:492)
data_ingester | [error] at
data_ingester | [error] stack trace is suppressed; run 'last Compile / run' for the full output
data_ingester | [error] (Compile / run) java.net.ConnectException: Connection refused (Connection refused)
data_ingester | [error] Total time: 122 s (02:02), completed Feb 10, 2022, 10:57:36 PM
The most common errors seem to be that you have specified the host incorrectly or not exposed the right ports, but since I can connect to the MySQL-container from the grafana-container I am inclined to believe both the host and ports are set correctly, so I am not sure what I am overlooking.
If you have made it through this far, thank you for reading, and any help is very appreciated!
(FYI: setting up a mysql db on localhost and running the Scala-program locally without docker and just connect to "localhost:3306" works, so it seems the code to actually connect seems to be alright, just that something breaks when running it using docker compose).

Why is my application not connecting to mysql?

I did docker-compose, but my application does not want to connect to the database. what could be the problem?
The application itself starts well, but as soon as I turn it into a container, it does not connect to the database and a lot of errors occur.
docker-compose:
version: '3.7'
services:
db:
image: mysql:8.0.17
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: 123test321
ports:
- 3306:3306
networks:
- employee-mysql
volumes:
- /home/alexey/temp/mysql01:/var/lib/mysql
adminer:
image: adminer
restart: always
ports:
- 3380:8080
webapp:
build:
context: .
restart: always
ports:
- 80:8080
networks:
- employee-mysql
depends_on:
- db
networks:
employee-mysql:
This is dockerfile:
FROM anapsix/alpine-java:8_jdk
FROM openjdk:8
ADD target/webapp-1.0.1.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
This is my log:
Starting work_db_1 ... done
Starting work_adminer_1 ... done
Starting work_webapp_1 ... done
Attaching to work_db_1, work_adminer_1, work_webapp_1
db_1 | 2019-09-09T17:29:20.983653Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
db_1 | 2019-09-09T17:29:20.983965Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.17) starting as process 1
db_1 | 2019-09-09T17:29:22.697164Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
db_1 | 2019-09-09T17:29:22.704622Z 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.
db_1 | 2019-09-09T17:29:22.807613Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.17' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
db_1 | 2019-09-09T17:29:23.019957Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
adminer_1 | PHP 7.3.9 Development Server started at Mon Sep 9 17:29:21 2019
webapp_1 | [INFO ] 2019-09-09 17:29:30.149 [main] ApplicationKt - Starting ApplicationKt v1.0.1 on d52aa0a7ff7e with PID 1 (/app.jar started by root in /)
webapp_1 | [INFO ] 2019-09-09 17:29:30.184 [main] ApplicationKt - No active profile set, falling back to default profiles: default
webapp_1 | [INFO ] 2019-09-09 17:29:38.634 [main] RepositoryConfigurationDelegate - Bootstrapping Spring Data repositories in DEFAULT mode.
webapp_1 | [INFO ] 2019-09-09 17:29:39.562 [main] RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 894ms. Found 19 repository interfaces.
webapp_1 | [INFO ] 2019-09-09 17:29:42.756 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$e8bed525] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:43.087 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration' of type [org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration$$EnhancerBySpringCGLIB$$816c9d5f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:43.130 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'objectPostProcessor' of type [org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:43.139 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#7d61eb55' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:43.159 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration' of type [org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerBySpringCGLIB$$a6414011] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:43.202 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.security.config.annotation.method.configuration.Jsr250MetadataSourceConfiguration' of type [org.springframework.security.config.annotation.method.configuration.Jsr250MetadataSourceConfiguration$$EnhancerBySpringCGLIB$$cb965827] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:43.237 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'jsr250MethodSecurityMetadataSource' of type [org.springframework.security.access.annotation.Jsr250MethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:43.244 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
webapp_1 | [INFO ] 2019-09-09 17:29:45.329 [main] HikariDataSource - HikariPool-1 - Starting...
webapp_1 | [ERROR] 2019-09-09 17:29:46.161 [main] HikariPool - HikariPool-1 - Exception during pool initialization.
webapp_1 | com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
webapp_1 |
webapp_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
All right.
version: '3.7'
services:
db:
image: mysql:8.0.17
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: ****
ports:
- 3306:3306
volumes:
- /home/alexey/temp/mysql01:/var/lib/mysql
adminer:
image: adminer
restart: always
ports:
- 3380:8080
webapp:
build:
context: .
environment:
CONTEXT_PATH: /a-test
DB_HOST: db
DB_PORT: 3306
DB_NAME: ****
DB_USER: ****
DB_PASSWORD: ****
MAIL_LOGIN: ****
MAIL_PASSWORD: ****
ports:
- 80:8080
depends_on:
- db
And Dockerfile:
FROM anapsix/alpine-java:8_jdk
FROM openjdk:8
ADD target/webapp-*.jar webapp.jar
EXPOSE 8080
ENTRYPOINT java -jar webapp.jar

Unable to link mysql docker container with spring boot application - Communications link failure

I am new to Docker. I am using Spring boot micro service. It's running well On my local machine. Now, I need to create a docker image for my application. It has a dependency on Mysql server. I am using docker-compose to create my containers. I am getting a communications link failure error while running my custom image (spring boot application). The Mysql image is running well independently.
My yml file :
version: '2'
services:
mysql-dev:
image: mysql:5.7
container_name: mysql-dev
environment:
MYSQL_ROOT_PASSWORD: "password"
MYSQL_DATABASE: "onlinetutorialspoint"
networks:
- my_mysql_net
ports:
- 3306:3308
spring_boot_db_service:
depends_on:
- mysql-dev
image: spring_boot_db_service
ports:
- 8181:8181
links:
- mysql-dev:mysql
networks:
- my_mysql_net
networks:
my_mysql_net:
driver: bridge
application properties file :
db.driver: com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://mysql-dev:3308/onlinetutorialspoint?useSSL=false
spring.datasource.username = root
spring.datasource.password = password
Full Error Message :
spring_boot_db_service_1 | 2019-01-28 13:34:06.955 INFO 1 --- [
main] org.hibernate.cfg.Environment : HHH000206:
hibernate.properties not found spring_boot_db_service_1 | 2019-01-28
13:34:07.000 INFO 1 --- [ main]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.0.1.Final} spring_boot_db_service_1 |
2019-01-28 13:34:08.430 WARN 1 --- [ main]
o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain
connection to query metadata : Communications link failure
spring_boot_db_service_1 | spring_boot_db_service_1 | The last
packet sent successfully to the server was 0 milliseconds ago. The
driver has not received any packets from the server.
spring_boot_db_service_1 | 2019-01-28 13:34:08.443 INFO 1 --- [
main] org.hibernate.dialect.Dialect : HHH000400: Using
dialect: org.hibernate.dialect.MySQL5Dialect spring_boot_db_service_1
| 2019-01-28 13:34:08.459 INFO 1 --- [ main]
o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000422: Disabling
contextual LOB creation as connection was null
spring_boot_db_service_1 | 2019-01-28 13:34:08.921 WARN 1 --- [
main] ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dbServiceImpl': Unsatisfied dependency
expressed through field 'dbServiceDao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dbServiceDaoImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception
is org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in class path
resource [com/htc/dbservice/configuration/DBConfiguration.class]:
Invocation of init method failed; nested exception is
org.hibernate.MappingException: Could not get constructor for
org.hibernate.persister.entity.SingleTableEntityPersister
spring_boot_db_service_1 | 2019-01-28 13:34:08.923 WARN 1 --- [
main] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy
method 'close' failed on bean with name 'eurekaRegistration':
org.springframework.beans.factory.BeanCreationNotAllowedException:
Error creating bean with name
'org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration':
Singleton bean creation not allowed while singletons of this factory
are in destruction (Do not request a bean from a BeanFactory in a
destroy method implementation!) spring_boot_db_service_1 | 2019-01-28
13:34:08.926 INFO 1 --- [ main]
o.apache.catalina.core.StandardService : Stopping service [Tomcat]
docker_spring_boot_db_service_1 exited with code 1
Did you change the default mysql port? if not, you are pointing to wrong port number.
When you map the port to pubilsh the service externally, the order is
<host-port>:<container-port>
services:
mysql-dev:
image: mysql:5.7
container_name: mysql-dev
environment:
MYSQL_ROOT_PASSWORD: "password"
MYSQL_DATABASE: "onlinetutorialspoint"
networks:
- my_mysql_net
ports:
- 3308:3306
And using docker-compose and connecting both services to the same network you can connect directly to the container without pubishing the mysql port to the external network.
Try to change your spring app pointing to mysql-dev:3306, or try to connect to the container spring_boot_db_service using
docker-compose exec spring_boot_db_service bash
and make a connectivity test to the database container.

SpringBoot on Docker unable to connect to MySQL

I have written docker compose for my SpringBoot app with MySQL. When I run docker-compose up eventually I get an error:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:325) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
... 69 common frames omitted
Caused by: 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:172) ~[mysql-connector-java-8.0.11.jar!/:8.0.11]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.11.jar!/:8.0.11]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862) ~[mysql-connector-java-8.0.11.jar!/:8.0.11]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:444) ~[mysql-connector-java-8.0.11.jar!/:8.0.11]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230) ~[mysql-connector-java-8.0.11.jar!/:8.0.11]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226) ~[mysql-connector-java-8.0.11.jar!/:8.0.11]
at java.sql.DriverManager.getConnection(DriverManager.java:664) ~[na:1.8.0_111]
at java.sql.DriverManager.getConnection(DriverManager.java:208) ~[na:1.8.0_111]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:196) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:159) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) ~[spring-jdbc-4.3.17.RELEASE.jar!/:4.3.17.RELEASE]
... 70 common frames omitted
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
At first I thought the the cause was the db but I managed to run local instance of the app and connect to the docker mysql.
Next I assumed that the spring app tries to connect to mysql before it is up and running but I restarted the app (mysql was already running) and got the same error.
Currently I think that this might be caused by the windows10 firewall but I am running low on ideas.
Dockerfile:
FROM java:8
LABEL maintainer="maciej"
WORKDIR /app
COPY target/kamienica.jar /app/kamienica.jar
ENTRYPOINT ["java", "-jar","kamienica.jar", "--spring.profiles.active=docker"]
docker-compose.yml
version: '3'
services:
mysql-docker-container:
image: mysql:latest
environment:
- MYSQL_ROOT_PASSWORD=maciej
- MYSQL_DATABASE=kamienica
- MYSQL_USER=maciej
- MYSQL_PASSWORD=maciej
volumes:
- /data/mysql
ports:
- 3333:3306
container_name: kamienica-db
kamienica-app:
image: kamienica-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mysql-docker-container
ports:
- 8080:8080
volumes:
- /data/spring-boot-app
container_name: kamienica-app
and the application-docker.properties:
jdbc.url = jdbc:mysql://kamienica-db:3333/kamienica?useSSL=false&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
jdbc.username = maciej
jdbc.password = maciej
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto=create-drop
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.current_session_context_class=thread
hibernate.connection.characterEncoding=UTF-8
hibernate.connection.charSet=UTF-8
Try to change the url into this your properties file
jdbc:mysql://mysql-docker-container:3306/kamienica
jdbc:mysql://[mysql-docker-container-name]:[mysql-port]/[db-name]
in your docker-compose.yml mysql-docker-container-name is mysql-docker-container
so change your spring boot application.properties file mysql url as following
jdbc:mysql://mysql-docker-container:3306/kamienica