With docker-compose, database container is not up and running - mysql

I am following this tutorial to setup spring boot project with docker-compose. Here is what I did:
My application.properties:
spring.datasource.url = jdbc:mysql://mysql-demo-container:3306/demo_db?useSSL=false
spring.datasource.username = root
spring.datasource.password =root
spring.datasource.tomcat.testWhileIdle = true
spring.datasource.tomcat.timeBetweenEvictionRunsMillis = 60000
spring.datasource.tomcat.validationQuery = SELECT 1
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
My Dockerfile:
`FROM java:8
LABEL maintainer=“foo.bar#gmail.com”
VOLUME /tmp
EXPOSE 8080
ADD target/spring-boot-data-jpa-example-0.0.1-SNAPSHOT.jar spring-boot-data-jpa-example-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","spring-boot-data-jpa-example-0.0.1-SNAPSHOT.jar"]`
I have this docker-compose.yml:
version: '3'
services:
mysql-demo-container:
image: mysql:latest
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=demo_db
- MYSQL_PASSWORD=myPass
ports:
- 2012:3306
volumes:
- /data/mysql
spring-boot-jpa-app:
image: spring-boot-jpa-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mysql-demo-container
ports:
- 8087:8080
volumes:
- /data/spring-boot-app
I firstly mvn clean install to build the project jar file, then I run docker-compose up to build images & hopefully run containers.
The logs:
$ docker-compose up
Creating network "spring-boot-data-jpa-example-master_default" with the default driver
Creating spring-boot-data-jpa-example-master_mysql-demo-container_1 ... done
Creating spring-boot-data-jpa-example-master_spring-boot-jpa-app_1 ... done
Attaching to spring-boot-data-jpa-example-master_mysql-demo-container_1, spring-boot-data-jpa-example-master_spring-boot-jpa-app_1
mysql-demo-container_1 | Initializing database
mysql-demo-container_1 | 2019-07-02T13:03:05.097872Z 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.
mysql-demo-container_1 | 2019-07-02T13:03:05.098037Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.16) initializing of server in progress as process 29
mysql-demo-container_1 | 2019-07-02T13:03:09.171833Z 5 [Warning] [MY-010453] [Server] root#localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
spring-boot-jpa-app_1 |
spring-boot-jpa-app_1 | . ____ _ __ _ _
spring-boot-jpa-app_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
spring-boot-jpa-app_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
spring-boot-jpa-app_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
spring-boot-jpa-app_1 | ' |____| .__|_| |_|_| |_\__, | / / / /
spring-boot-jpa-app_1 | =========|_|==============|___/=/_/_/_/
spring-boot-jpa-app_1 | :: Spring Boot :: (v1.5.9.RELEASE)
spring-boot-jpa-app_1 |
spring-boot-jpa-app_1 | 2019-07-02 13:03:11.516 INFO 1 --- [ main] .s.e.SpringBootDataJpaExampleApplication : Starting SpringBootDataJpaExampleApplication v0.0.1-SNAPSHOT on 3c0d94b76fd6 with PID 1 (/spring-boot-data-jpa-example-0.0.1-SNAPSHOT.jar started by root in /)
spring-boot-jpa-app_1 | 2019-07-02 13:03:11.556 INFO 1 --- [ main] .s.e.SpringBootDataJpaExampleApplication : No active profile set, falling back to default profiles: default
spring-boot-jpa-app_1 | 2019-07-02 13:03:11.979 INFO 1 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6d5380c2: startup date [Tue Jul 02 13:03:11 UTC 2019]; root of context hierarchy
mysql-demo-container_1 | 2019-07-02T13:03:13.525348Z 0 [System] [MY-013170] [Server] /usr/sbin/mysqld (mysqld 8.0.16) initializing of server has completed
mysql-demo-container_1 | Database initialized
mysql-demo-container_1 | MySQL init process in progress...
mysql-demo-container_1 | MySQL init process in progress...
mysql-demo-container_1 | MySQL init process in progress...
mysql-demo-container_1 | 2019-07-02T13:03:15.636380Z 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.
mysql-demo-container_1 | 2019-07-02T13:03:15.636539Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.16) starting as process 80
mysql-demo-container_1 | 2019-07-02T13:03:18.070695Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysql-demo-container_1 | 2019-07-02T13:03:18.081045Z 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.
mysql-demo-container_1 | 2019-07-02T13:03:18.152808Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.16' socket: '/var/run/mysqld/mysqld.sock' port: 0 MySQL Community Server - GPL.
mysql-demo-container_1 | 2019-07-02T13:03:18.311442Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock'
spring-boot-jpa-app_1 | 2019-07-02 13:03:20.039 INFO 1 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
spring-boot-jpa-app_1 | 2019-07-02 13:03:20.221 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
spring-boot-jpa-app_1 | 2019-07-02 13:03:20.232 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
spring-boot-jpa-app_1 | 2019-07-02 13:03:21.210 INFO 1 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
spring-boot-jpa-app_1 | 2019-07-02 13:03:21.213 INFO 1 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 9251 ms
spring-boot-jpa-app_1 | 2019-07-02 13:03:22.153 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
spring-boot-jpa-app_1 | 2019-07-02 13:03:22.169 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
spring-boot-jpa-app_1 | 2019-07-02 13:03:22.178 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
spring-boot-jpa-app_1 | 2019-07-02 13:03:22.178 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
spring-boot-jpa-app_1 | 2019-07-02 13:03:22.181 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
mysql-demo-container_1 | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
mysql-demo-container_1 | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
spring-boot-jpa-app_1 | 2019-07-02 13:03:25.161 ERROR 1 --- [ main] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
spring-boot-jpa-app_1 |
spring-boot-jpa-app_1 | com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
spring-boot-jpa-app_1 |
spring-boot-jpa-app_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-jpa-app_1 | at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:989) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2222) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2017) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_111]
spring-boot-jpa-app_1 | at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330) ~[mysql-connector-java-5.1.44.jar!/:5.1.44]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:310) ~[tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:735) [tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:667) [tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:482) [tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:154) [tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.23.jar!/:na]
spring-boot-jpa-app_1 | at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) [spring-jdbc-4.3.13.RELEASE.jar!/:4.3.13.RELEASE]
spring-boot-jpa-app_1 | at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) [spring-jdbc-4.3.13.RELEASE.jar!/:4.3.13.RELEASE]
spring-boot-jpa-app_1 | at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:326) [spring-jdbc-4.3.13.RELEASE.jar!/:4.3.13.RELEASE]
spring-boot-jpa-app_1 | at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:366) [spring-jdbc-4.3.13.RELEASE.jar!/:4.3.13.RELEASE]
spring-boot-jpa-app_1 | at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:72) [spring-boot-autoconfigure-1.5.9.RELEASE.jar!/:1.5.9.RELEASE]
spring-boot-jpa-app_1 | at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:139) [spring-boot-autoconfigure-1.5.9.
As you can see from the beginning of the log, the containers seem created successfully.
Run docker ps shows me:
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8fa64acb363d mysql:latest "docker-entrypoint.s…" 30 minutes ago Up 30 minutes 33060/tcp, 0.0.0.0:2012->3306/tcp spring-boot-data-jpa-example-master_mysql-demo-container_1
What could be the reason for the error?

You should be aware of this very important footnote in the reference documentation of Docker Compose:
depends_on does not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.
In your case, your Spring boot container starts right after your MySQL container is being started. There's no guarantee though that MySQL will be able to take connections when Spring boot is setting up its connection pool.
This means that your Spring boot connection will fail to startup, because MySQL isn't ready yet. This results in your application container to be killed.
The solution to this problem is mentioned within the documentation I quoted. Namely, you have to use some kind of polling mechanism to see if you can connect to your database or not.
If you don't want to use tools like wait-for-it or wait-for, you could write a simple Shell script that does something like this:
while ! exec 6<>/dev/tcp/mysql-demo-container/3306; do
echo "Trying to connect to MySQL..."
sleep 10
done
exec java -jar spring-boot-data-jpa-example-0.0.1-SNAPSHOT.jar
This also means you have to change the ENTRYPOINT within your Dockerfile to refer to such shell script rather than directly running your JAR file.

Related

Spring boot app cant connect to mysql db - docker-compose

I tried many ways and every time the application runs in the container I get such errors:
WARN 1 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata
java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
my docker-compose:
version: '3.8'
networks:
my_network:
external: true
services:
mysql:
container_name: configs_mysql
image: mysql:latest
restart: always
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: scrap
MYSQL_USER: scrap
MYSQL_PASSWORD: scrap
MYSQL_DATABASE: configs
networks:
- my_network
web:
build: .
image: scrapyconfigmanager_web
ports:
- "8181:8181"
networks:
- my_network
depends_on:
- mysql
my Dockerfile:
FROM openjdk:11
# Copy source code to temporary building location
WORKDIR /source_code
COPY . .
RUN ./gradlew bootJar
WORKDIR /scrapy
RUN cp /source_code/build/libs/ScrapyConfigManager-1.0.jar .
EXPOSE 8181
ENTRYPOINT ["java","-jar","ScrapyConfigManager-1.0.jar"]
my hibernate.cfg:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://configs_mysql:3306/configs</property>
<property name="hibernate.connection.username">scrap</property>
<property name="hibernate.connection.password">scrap</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<mapping class="org.scrapeusz.model.OlxCar" />
</session-factory>
</hibernate-configuration>
Both containers start up, but after a while the spring container stops.
Below I paste part of the code from the terminal after the "docker-compose up" command:
Creating configs_mysql ... done
Creating scrapyconfigmanager_web_1 ... done
Attaching to configs_mysql, scrapyconfigmanager_web_1
configs_mysql | 2022-07-21 10:34:49+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
configs_mysql | 2022-07-21 10:34:49+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
configs_mysql | 2022-07-21 10:34:49+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
configs_mysql | 2022-07-21 10:34:49+00:00 [Note] [Entrypoint]: Initializing database files
configs_mysql | 2022-07-21T10:34:49.504138Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.29) initializing of server in progress as process 42
configs_mysql | 2022-07-21T10:34:49.515175Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
configs_mysql | 2022-07-21T10:34:49.795876Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
web_1 |
web_1 | . ____ _ __ _ _
web_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
web_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
web_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
web_1 | ' |____| .__|_| |_|_| |_\__, | / / / /
web_1 | =========|_|==============|___/=/_/_/_/
web_1 | :: Spring Boot :: (v2.6.6)
web_1 |
web_1 | 2022-07-21 10:34:50.905 INFO 1 --- [ main] org.scrapeusz.ScrapyConfigManager : Starting ScrapyConfigManager using Java 11.0.15 on 71d7d66bbd3b with PID 1 (/scrapy/ScrapyConfigManager-1.0.jar started by root in /scrapy)
web_1 | 2022-07-21 10:34:50.910 INFO 1 --- [ main] org.scrapeusz.ScrapyConfigManager : No active profile set, falling back to 1 default profile: "default"
configs_mysql | 2022-07-21T10:34:51.393524Z 6 [Warning] [MY-010453] [Server] root#localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
web_1 | 2022-07-21 10:34:52.239 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
web_1 | 2022-07-21 10:34:52.255 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
web_1 | 2022-07-21 10:34:52.255 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
web_1 | 2022-07-21 10:34:52.364 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
web_1 | 2022-07-21 10:34:52.364 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1388 ms
web_1 | 2022-07-21 10:34:52.577 INFO 1 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 6.0.0.Final
web_1 | 2022-07-21 10:34:53.269 WARN 1 --- [ main] org.hibernate.orm.connections.pooling : HHH10001002: Using built-in connection pool (not intended for production use)
web_1 | 2022-07-21 10:34:53.275 INFO 1 --- [ main] org.hibernate.orm.connections.pooling : HHH10001005: Loaded JDBC driver class: com.mysql.cj.jdbc.Driver
web_1 | 2022-07-21 10:34:53.275 INFO 1 --- [ main] org.hibernate.orm.connections.pooling : HHH10001012: Connecting with JDBC URL [jdbc:mysql://configs_mysql:3306/configs]
web_1 | 2022-07-21 10:34:53.275 INFO 1 --- [ main] org.hibernate.orm.connections.pooling : HHH10001001: Connection properties: {password=****, user=scrap}
web_1 | 2022-07-21 10:34:53.276 INFO 1 --- [ main] org.hibernate.orm.connections.pooling : HHH10001003: Autocommit mode: false
web_1 | 2022-07-21 10:34:53.279 INFO 1 --- [ main] org.hibernate.orm.connections.pooling : HHH10001115: Connection pool size: 20 (min=1)
web_1 | 2022-07-21 10:34:53.407 WARN 1 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata
web_1 |
web_1 | java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
web_1 | at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:259) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:284) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:177) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:36) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:100) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:255) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:230) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
web_1 | at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:48) ~[hibernate-core-6.0.0.Final.jar!/:6.0.0.Final]
The issue is with your hibernate.cfg file.
You are referring container name as database host in that config file.
<property name="hibernate.connection.url">jdbc:mysql://configs_mysql:3306/configs</property>
configs_mysql is your container name but it not your DB host in the docker world. Remember communication between the docker containers inside the docker compose network will happen through service name.
For Database service you defined mysql as your service name.
Change the hibernate.connection.url to below
<property name="hibernate.connection.url">jdbc:mysql://mysql:3306/configs</property>
Refer: Docker compose with multiple services (app and DB)

MYSQL Communications link failure with Docker compose Spring Boot Config Server

My book-service unable to connect mysql-server in docker compose. Check below log.
It was working one day ago, but today its not working, even I have not touched single line of code.
This is my docker file, book-service property file and Log traces.
version: '3.1'
services:
MYSQL-SERVER:
image: mysql
container_name: MYSQL-SERVER
environment:
- MYSQL_ROOT_PASSWORD=root
volumes:
- ./docker:/docker-entrypoint-initdb.d
ports:
- 3307:3306
networks:
- spring-cloud-network
command: --default-authentication-plugin=mysql_native_password
config-server:
container_name: config-server
build:
context: config-server
dockerfile: Dockerfile
image: demo/config-server-service:latest
depends_on:
- MYSQL-SERVER
environment:
- spring.profiles.active=native
- spring.cloud.config.server.native.search-locations=config-store
ports:
- 8888:8888
networks:
- spring-cloud-network
eureka-server:
container_name: eureka-server
build:
context: eureka-server
dockerfile: Dockerfile
image: demo/eureka-server-service:latest
environment:
- spring.cloud.config.uri=http://config-server:8888
depends_on:
- config-server
restart: always
ports:
- 8761:8761
networks:
- spring-cloud-network
book-service:
container_name: book-service
build:
context: book-service
dockerfile: Dockerfile
image: demo/book-service:latest
environment:
- db.host=MYSQL-SERVER
- db.port=3306
- db.name=demo_book_schema
- db.username=root
- db.password=root
- EUREKA_HOST_URL=http://eureka-server:8761/eureka
- spring.cloud.config.uri=http://config-server:8888
- logging.level.=DEBUG
depends_on:
- config-server
- eureka-server
- MYSQL-SERVER
restart: on-failure
ports:
- 8011:8011
networks:
- spring-cloud-network
volumes:
database:
driver: local
networks:
spring-cloud-network:
driver: bridge
Property File book-service:
app.version=1.0
db.host=localhost
db.port=3306
db.name=demo_book_schema
db.username=root
db.password=root
spring.datasource.url=jdbc:mysql://${db.host}:${db.port}/${db.name}?createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=${db.username}
spring.datasource.password=${db.password}
#Hibernates Properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=false
spring.flyway.schemas=${db.name}
spring.flyway.locations=classpath:db/migration
eureka.client.serviceUrl.defaultZone=${EUREKA_HOST_URL:http://localhost:8761/eureka/}
eureka.client.registerWithEureka = true
eureka.client.fetchRegistry = true
eureka.instance.leaseRenewalIntervalInSeconds=1
eureka.instance.leaseExpirationDurationInSeconds=2
eureka.client.healthcheck.enabled=true
eureka.client.lease.duration=5
logging.level.com.kapilsony.userservice.logging=DEBUG
Logs:-
. ____ _ __ _ _
/\ / _' __ _ () __ __ _ \ \ \ \
( ( )___ | '_ | '| | ' / _` | \ \ \ \
\/ __)| |)| | | | | || (_| | ) ) ) )
' |__| .__|| ||| |__, | / / / /
=========||==============|__/=///_/
:: Spring Boot :: (v2.5.1)
2021-07-31 20:27:50.999 INFO 1 --- [ main]
c.c.c.ConfigServicePropertySourceLocator : Fetching config from server
at : http://config-server:8888
2021-07-31 20:27:51.244 INFO 1 --- [ main]
c.c.c.ConfigServicePropertySourceLocator : Located environment:
name=book-service, profiles=[default], label=session2, version=null,
state=null
2021-07-31 20:27:51.247 INFO 1 --- [ main]
b.c.PropertySourceBootstrapConfiguration : Located property source:
[BootstrapPropertySource {name='bootstrapProperties-configClient'},
BootstrapPropertySource
{name='bootstrapProperties-file:config-store/book-service.properties'}]
2021-07-31 20:27:51.278 INFO 1 --- [ main]
c.k.bookservice.BookserviceApplication : No active profile set,
falling back to default profiles: default
2021-07-31 20:27:53.239 INFO 1 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA repositories in DEFAULT mode.
2021-07-31 20:27:53.602 INFO 1 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 349 ms. Found 1 JPA repository interfaces.
2021-07-31 20:27:54.257 INFO 1 --- [ main]
o.s.cloud.context.scope.GenericScope : BeanFactory
id=7c3a88a8-133e-3e51-9c38-54b1877995f3
2021-07-31 20:27:55.713 INFO 1 --- [ main]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8021 (http)
2021-07-31 20:27:55.841 INFO 1 --- [ main]
w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext:
initialization completed in 4516 ms
2021-07-31 20:27:56.609 INFO 1 --- [ main]
o.f.c.internal.license.VersionPrinter : Flyway Community Edition
7.10.0 by Redgate
2021-07-31 20:27:56.643 INFO 1 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-07-31 20:27:57.888 ERROR 1 --- [ main]
com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during
pool initialization.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications
link failure
The last packet sent successfully to the server was 0 milliseconds
ago. The driver has not received any packets from the server.
at
com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:833)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:453)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
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.(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.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:55)
[flyway-core-7.10.0.jar!/:na]
at
org.flywaydb.core.internal.jdbc.JdbcConnectionFactory.(JdbcConnectionFactory.java:68)
[flyway-core-7.10.0.jar!/:na]
at org.flywaydb.core.Flyway.execute(Flyway.java:510)
[flyway-core-7.10.0.jar!/:na]
at org.flywaydb.core.Flyway.migrate(Flyway.java:170)
[flyway-core-7.10.0.jar!/:na]
at
org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66)
[spring-boot-autoconfigure-2.5.1.jar!/:2.5.1]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
~[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
[spring-beans-5.3.8.jar!/:5.3.8]
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154)
~[spring-context-5.3.8.jar!/:5.3.8]
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908)
~[spring-context-5.3.8.jar!/:5.3.8]
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
~[spring-context-5.3.8.jar!/:5.3.8]
at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
~[spring-boot-2.5.1.jar!/:2.5.1]
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
~[spring-boot-2.5.1.jar!/:2.5.1]
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434)
~[spring-boot-2.5.1.jar!/:2.5.1]
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:338)
~[spring-boot-2.5.1.jar!/:2.5.1]
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1343)
~[spring-boot-2.5.1.jar!/:2.5.1]
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1332)
~[spring-boot-2.5.1.jar!/:2.5.1]
at
com.kapilsony.bookservice.BookserviceApplication.main(BookserviceApplication.java:23)
~[classes!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
~[na:1.8.0_292]
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_292]
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_292]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_292]
at
org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49)
~[bookservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:108)
~[bookservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
~[bookservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at
org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88)
~[bookservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
Caused by: com.mysql.cj.exceptions.CJCommunicationsException:
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 sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) ~[na:1.8.0_292]
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
~[na:1.8.0_292]
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
~[na:1.8.0_292]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
~[na:1.8.0_292]
at
com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:89)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at com.mysql.cj.NativeSession.connect(NativeSession.java:144)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:953)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:823)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
... 43 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection
refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
~[na:1.8.0_292]
at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
~[na:1.8.0_292]
at
java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
~[na:1.8.0_292]
at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
~[na:1.8.0_292]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
~[na:1.8.0_292]
at java.net.Socket.connect(Socket.java:607) ~[na:1.8.0_292]
at
com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
at
com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63)
~[mysql-connector-java-8.0.25.jar!/:8.0.25]
... 46 common frames omitted
2021-07-31 20:27:57.893 WARN 1 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'flywayInitializer' defined in class path
resource
[org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]:
Invocation of init method failed; nested exception is
org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to obtain connection from database: 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.
SQL State : 08S01
Error Code : 0
Message : 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.
I'm providing proper DataSource Properties using docker environment:-
db.host=MYSQL-SERVER
db.port=3306
db.name=demo_book_schema
db.username=root
db.password=root

Spring Boot, Java, Docker Compose, Getting 'Connection refused' while trying to make connection between two container (mysql, my-api)

When I execute the docker-compose up command, the following error is generated:
Caused by: java.net.ConnectException: Connection refused
I am trying to establish a connection between two containers, MySQL and My-API container, using docker-compose, but it is somehow not connecting. Here is the docker-compose.yml:
version: '3'
services:
discovery-mysql:
image: mysql:5.7.34
container_name: discovery-mysql
environment:
- MYSQL_ROOT_PASSWORD=tomo
- MYSQL_DATABASE=r2dbc
ports:
- 3307:3306
networks:
- common-network
flyway:
image: flyway/flyway
command:
- url=jdbc:mysql://discovery-mysql:3306/r2dbc?useUnicode=true&characterEncoding=utf8&useSSL=false -user=root -password=tomo migrate
volumes:
- ./src/main/resources/db/migration:/flyway/sql
- ./flyway/conf/flyway.config:/flyway.config
depends_on:
- discovery-mysql
networks:
- common-network
discovery-app:
image: tomojava3284/helloworldapi:latest
restart: on-failure
depends_on:
- discovery-mysql
ports:
- 8001:8080
environment:
- spring.datasource.url=r2dbc:mysql://root:tomo#discovery-mysql:3306/r2dbc
networks:
- common-network
networks:
common-network:
driver: bridge
Things that I had tried:
I added networks: -common-network to put into the same network, but didn't work. I don't see anything wrong with the URL r2dbc:mysql://root:tomo#discovery-mysql:3306/r2dbc.
By the way, when I run the program locally on IDE (not using docker-compose up), given the url=r2dbc:mysql://root:tomo#127.0.0.1:3306/r2dbc, it works fine.
I have seen similar threads on stack overflow, but many of their solutions didn't work (I specified in the "Things that I had tried" section).
What could be the reason that the lead to the error Caused by: java.net.ConnectException: Connection refused?
Here are the full details of errors:
C:\Users\me\github\HelloWorld>docker-compose up
WARNING: Found orphan containers (mysql) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
Starting discovery-mysql ... done
Starting helloworld_flyway_1 ... done
Starting helloworld_discovery-app_1 ... done
Attaching to discovery-mysql, helloworld_flyway_1, helloworld_discovery-app_1
discovery-mysql | 2021-06-23 16:03:23+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.34-1debian10 started.
discovery-mysql | 2021-06-23 16:03:23+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
discovery-mysql | 2021-06-23 16:03:23+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.34-1debian10 started.
discovery-mysql | 2021-06-23T16:03:23.899462Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
discovery-mysql | 2021-06-23T16:03:23.900841Z 0 [Note] mysqld (mysqld 5.7.34) starting as process 1 ...
discovery-mysql | 2021-06-23T16:03:23.903779Z 0 [Note] InnoDB: PUNCH HOLE support available
discovery-mysql | 2021-06-23T16:03:23.903816Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
discovery-mysql | 2021-06-23T16:03:23.903821Z 0 [Note] InnoDB: Uses event mutexes
discovery-mysql | 2021-06-23T16:03:23.903824Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
discovery-mysql | 2021-06-23T16:03:23.903827Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
discovery-mysql | 2021-06-23T16:03:23.903829Z 0 [Note] InnoDB: Using Linux native AIO
discovery-mysql | 2021-06-23T16:03:23.904263Z 0 [Note] InnoDB: Number of pools: 1
discovery-mysql | 2021-06-23T16:03:23.904371Z 0 [Note] InnoDB: Using CPU crc32 instructions
discovery-mysql | 2021-06-23T16:03:23.905996Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
discovery-mysql | 2021-06-23T16:03:23.914593Z 0 [Note] InnoDB: Completed initialization of buffer pool
discovery-mysql | 2021-06-23T16:03:23.916694Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
discovery-mysql | 2021-06-23T16:03:23.928540Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
discovery-mysql | 2021-06-23T16:03:23.947396Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
discovery-mysql | 2021-06-23T16:03:23.947471Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
discovery-mysql | 2021-06-23T16:03:23.978325Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
discovery-mysql | 2021-06-23T16:03:23.978805Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
discovery-mysql | 2021-06-23T16:03:23.978846Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
discovery-mysql | 2021-06-23T16:03:23.979683Z 0 [Note] InnoDB: 5.7.34 started; log sequence number 12664810
discovery-mysql | 2021-06-23T16:03:23.979948Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
discovery-mysql | 2021-06-23T16:03:23.980060Z 0 [Note] Plugin 'FEDERATED' is disabled.
discovery-mysql | 2021-06-23T16:03:23.982100Z 0 [Note] InnoDB: Buffer pool(s) load completed at 210623 16:03:23
discovery-mysql | 2021-06-23T16:03:23.984495Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
discovery-mysql | 2021-06-23T16:03:23.984525Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
discovery-mysql | 2021-06-23T16:03:23.985024Z 0 [Warning] CA certificate ca.pem is self signed.
discovery-mysql | 2021-06-23T16:03:23.985071Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
discovery-mysql | 2021-06-23T16:03:23.985582Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
discovery-mysql | 2021-06-23T16:03:23.985650Z 0 [Note] IPv6 is available.
discovery-mysql | 2021-06-23T16:03:23.985661Z 0 [Note] - '::' resolves to '::';
discovery-mysql | 2021-06-23T16:03:23.985676Z 0 [Note] Server socket created on IP: '::'.
discovery-mysql | 2021-06-23T16:03:23.992611Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
discovery-mysql | 2021-06-23T16:03:23.999904Z 0 [Note] Event Scheduler: Loaded 0 events
discovery-mysql | 2021-06-23T16:03:24.000165Z 0 [Note] mysqld: ready for connections.
discovery-mysql | Version: '5.7.34' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL)
flyway_1 | ERROR: Invalid argument: url=jdbc:mysql://discovery-mysql:3306/r2dbc?useUnicode=true&characterEncoding=utf8&useSSL=false -user=root -password=tomo migrate
helloworld_flyway_1 exited with code 1
discovery-app_1 |
discovery-app_1 | . ____ _ __ _ _
discovery-app_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
discovery-app_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
discovery-app_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
discovery-app_1 | ' |____| .__|_| |_|_| |_\__, | / / / /
discovery-app_1 | =========|_|==============|___/=/_/_/_/
discovery-app_1 | :: Spring Boot :: (v2.5.0)
discovery-app_1 |
discovery-app_1 | 2021-06-23 16:03:25.501 INFO 1 --- [ main] c.t.HelloWorld.HelloWorldApplication : Starting HelloWorldApplication v0.0.1-SNAPSHOT using Java 16.0.1 on 1d485fdb3de3 with PID 1
(/app.jar started by root in /)
discovery-app_1 | 2021-06-23 16:03:25.503 INFO 1 --- [ main] c.t.HelloWorld.HelloWorldApplication : No active profile set, falling back to default profiles: default
discovery-app_1 | 2021-06-23 16:03:26.119 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data R2DBC repositories in DEFAULT mode.
discovery-app_1 | 2021-06-23 16:03:26.242 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 118 ms. Found 1 R2DBC repository interfaces.
discovery-app_1 | ****************************************************************************************************************
discovery-app_1 | r2dbc:mysql://root:tomo#discovery-mysql:3306/r2dbc // System.out.println(#Value("${spring.datasource.url}"))
discovery-app_1 | ****************************************************************************************************************
discovery-app_1 | 2021-06-23 16:03:27.354 INFO 1 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 7.10.0 by Redgate
discovery-app_1 | 2021-06-23 16:03:27.469 WARN 1 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.spring
framework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfi
guration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
discovery-app_1 | Unable to obtain connection from database: Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------
discovery-app_1 | SQL State : 08S01
discovery-app_1 | Error Code : 0
discovery-app_1 | Message : Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 |
discovery-app_1 | 2021-06-23 16:03:27.485 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener :
discovery-app_1 |
discovery-app_1 | Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
discovery-app_1 | 2021-06-23 16:03:27.505 ERROR 1 --- [ main] o.s.boot.SpringApplication : Application run failed
discovery-app_1 |
discovery-app_1 | org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/Flyw
ayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
discovery-app_1 | Unable to obtain connection from database: Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------
discovery-app_1 | SQL State : 08S01
discovery-app_1 | Error Code : 0
discovery-app_1 | Message : Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 |
discovery-app_1 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:64) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1 | at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1 | at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:438) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1 | at org.springframework.boot.SpringApplication.run(SpringApplication.java:337) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1 | at org.springframework.boot.SpringApplication.run(SpringApplication.java:1336) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1 | at org.springframework.boot.SpringApplication.run(SpringApplication.java:1325) ~[spring-boot-2.5.0.jar!/:2.5.0]
discovery-app_1 | at com.tomoaki3284.HelloWorld.HelloWorldApplication.main(HelloWorldApplication.java:11) ~[classes!/:0.0.1-SNAPSHOT]
discovery-app_1 | at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
discovery-app_1 | at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
discovery-app_1 | at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
discovery-app_1 | at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
discovery-app_1 | at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1 | at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1 | at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1 | at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[app.jar:0.0.1-SNAPSHOT]
discovery-app_1 | Caused by: org.flywaydb.core.internal.exception.FlywaySqlException:
discovery-app_1 | Unable to obtain connection from database: Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------
discovery-app_1 | SQL State : 08S01
discovery-app_1 | Error Code : 0
discovery-app_1 | Message : Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 |
discovery-app_1 | at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:71) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1 | at org.flywaydb.core.internal.jdbc.JdbcConnectionFactory.<init>(JdbcConnectionFactory.java:68) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1 | at org.flywaydb.core.Flyway.execute(Flyway.java:510) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1 | at org.flywaydb.core.Flyway.migrate(Flyway.java:170) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1 | at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-2.5.0.jar!/:2.5.0]
discovery-app_1 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-5.3.7.jar!/:5.3.7]
discovery-app_1 | ... 24 common frames omitted
discovery-app_1 | Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 | at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:833) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:453) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at org.springframework.jdbc.datasource.SimpleDriverDataSource.getConnectionFromDriver(SimpleDriverDataSource.java:144) ~[spring-jdbc-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205) ~[spring-jdbc-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169) ~[spring-jdbc-5.3.7.jar!/:5.3.7]
discovery-app_1 | at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:55) ~[flyway-core-7.10.0.jar!/:na]
discovery-app_1 | ... 30 common frames omitted
discovery-app_1 | Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
discovery-app_1 |
discovery-app_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
discovery-app_1 | at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
discovery-app_1 | at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78) ~[na:na]
discovery-app_1 | at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
discovery-app_1 | at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na]
discovery-app_1 | at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na]
discovery-app_1 | at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:89) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.NativeSession.connect(NativeSession.java:144) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:953) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:823) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | ... 37 common frames omitted
discovery-app_1 | Caused by: java.net.ConnectException: Connection refused
discovery-app_1 | at java.base/sun.nio.ch.Net.connect0(Native Method) ~[na:na]
discovery-app_1 | at java.base/sun.nio.ch.Net.connect(Net.java:576) ~[na:na]
discovery-app_1 | at java.base/sun.nio.ch.Net.connect(Net.java:565) ~[na:na]
discovery-app_1 | at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588) ~[na:na]
discovery-app_1 | at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
discovery-app_1 | at java.base/java.net.Socket.connect(Socket.java:645) ~[na:na]
discovery-app_1 | at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63) ~[mysql-connector-java-8.0.25.jar!/:8.0.25]
discovery-app_1 | ... 40 common frames omitted
discovery-app_1 |
// from here, the same log repeatedly because Spring Boot App would restart on failure.
How I am pushing changes every time:
mvnw package && java -jar target/spring-boot-0.0.1-SNAPSHOT.jar
docker build -t tomojava3284/helloworldapi .
docker push tomojava3284/helloworldapi:latest
docker-compose pull
docker-compose up
I think there is a bug there when accessing the database by service name. as a solution I can suggest you use host.docker.internal.
then the URL will be like the below. it will not be a problem in the production mode due to using a managed database.
- spring.datasource.url=r2dbc:mysql://root:tomo#host.docker.internal:3306/r2dbc
https://docs.docker.com/desktop/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
I had a same problem with java and my solution for this issue was setting IP for each service in docker-compose.yml like this :
version: '3'
services:
discovery-mysql:
image: mysql:5.7.34
container_name: discovery-mysql
environment:
- MYSQL_ROOT_PASSWORD=tomo
- MYSQL_DATABASE=r2dbc
ports:
- 3307:3306
networks:
common-network:
ipv4_address: 172.18.0.5
flyway:
image: flyway/flyway
command:
- url=jdbc:mysql://discovery-mysql:3306/r2dbc?useUnicode=true&characterEncoding=utf8&useSSL=false -user=root -password=tomo migrate
volumes:
- ./src/main/resources/db/migration:/flyway/sql
- ./flyway/conf/flyway.config:/flyway.config
depends_on:
- discovery-mysql
networks:
common-network:
ipv4_address: 172.18.0.10
discovery-app:
image: tomojava3284/helloworldapi:latest
restart: on-failure
depends_on:
- discovery-mysql
ports:
- 8001:8080
environment:
- spring.datasource.url=r2dbc:mysql://root:tomo#discovery-mysql:3306/r2dbc
networks:
common-network:
ipv4_address: 172.18.0.15
networks:
common-network:
ipam:
config:
- subnet: 172.18.0.0/16
And your connect url will be
$ r2dbc:mysql://root:tomo# 172.18.0.5:3306/r2dbc
Be careful what IP range you use, maybe this one is no longer free

Docker compose runs containers wrong way

I need to run Spring boot app container with mysql docker container using docker compose on Ubuntu. I have simple REST controller, configured database in application.properties file. Also I created Dockerfile for Spring boot app image and docker-compose.yml file.
But when I launch it with docker-compose up Spring app container logs show me that Tomcat started on port(s): 8086 (http) with context path '', but I set port 10222 in docker-compose.yml and application.properties.When I try to launch
http://localhost:8086/all/create or
http://localhost:10222/all/create it is not working.
I don't understand why docker sets its own port instead of my value and I can't test request in Postman. I configured docker to work without sudo in Ubuntu.
Code:
Resource.java
#RestController
#RequestMapping("/all")
public class Resource {
#Autowired
private UserRepository userRepository;
#GetMapping("/")
public List<Users> all() {
return userRepository.findAll();
}
#GetMapping("/create")
public List<Users> users() {
Users users = new Users();
users.setId(1);
users.setName("Sam");
users.setSalary(3400);
users.setTeamName("Development");
userRepository.save(users);
return userRepository.findAll();
}
}
application.properties
spring.datasource.url=jdbc:mysql://docker-mysql:3306/test_docker
spring.datasource.username = root
spring.datasource.password = password
server.port=10222
# spring.datasource.initialization-mode= always
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Dockerfile
FROM openjdk:8
COPY target/users-mysql.jar users-mysql.jar
ENTRYPOINT ["java","-jar","users-mysql.jar"]
docker-compose.yml
version: "3"
services:
docker-mysql:
restart: always
container_name: docker-mysql
image: mysql
environment:
MYSQL_DATABASE: test_docker
MYSQL_ROOT_PASSWORD: password
MYSQL_USER: root
MYSQL_PASSWORD: password
volumes:
- ./sql:/docker-entrypoint-initdb.d
ports:
- "6033:3306"
users-mysql:
restart: on-failure
build: ./
expose:
- "10222"
ports:
- 10222:10222
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://docker-mysql:3306/test_docker?autoReconnect=true
depends_on:
- docker-mysql
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ru.aplaksin</groupId>
<artifactId>docker-mysql-spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>docker-mysql-spring-boot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<finalName>users-mysql</finalName>
</configuration>
</plugin>
</plugins>
</build>
</project>
users.sql
DROP TABLE IF EXISTS `author`;
CREATE TABLE `author` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`salary` int(11) NOT NULL,
`team_name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Upd. logs:
Building users-mysql
Step 1/3 : FROM openjdk:8
---> 0d54b885dc70
Step 2/3 : COPY target/users-mysql.jar users-mysql.jar
---> Using cache
---> aa455cd3a786
Step 3/3 : ENTRYPOINT ["java","-jar","users-mysql.jar"]
---> Using cache
---> 13bbd75347b6
Successfully built 13bbd75347b6
Successfully tagged docker-mysql-spring-boot_users-mysql:latest
Starting docker-mysql ... done
Starting docker-mysql-spring-boot_users-mysql_1 ... done
Attaching to docker-mysql, docker-mysql-spring-boot_users-mysql_1
docker-mysql | 2020-04-15 19:48:08+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.19-1debian10 started.
docker-mysql | 2020-04-15 19:48:13+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
docker-mysql | 2020-04-15 19:48:14+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.19-1debian10 started.
docker-mysql | 2020-04-15T19:48:15.128671Z 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.
docker-mysql | 2020-04-15T19:48:15.175038Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.19) starting as process 1
docker-mysql | 2020-04-15T19:48:24.153392Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
docker-mysql | 2020-04-15T19:48:24.300883Z 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.
docker-mysql | 2020-04-15T19:48:24.943425Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.19' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
docker-mysql | 2020-04-15T19:48:25.237539Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
users-mysql_1 |
users-mysql_1 | . ____ _ __ _ _
users-mysql_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
users-mysql_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
users-mysql_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
users-mysql_1 | ' |____| .__|_| |_|_| |_\__, | / / / /
users-mysql_1 | =========|_|==============|___/=/_/_/_/
users-mysql_1 | :: Spring Boot :: (v2.2.6.RELEASE)
users-mysql_1 |
users-mysql_1 | 2020-04-15 19:48:27.616 INFO 1 --- [ main] r.a.d.DockerMysqlSpringBootApplication : Starting DockerMysqlSpringBootApplication v0.0.1-SNAPSHOT on d44ee3620b39 with PID 1 (/users-mysql.jar started by root in /)
users-mysql_1 | 2020-04-15 19:48:27.650 INFO 1 --- [ main] r.a.d.DockerMysqlSpringBootApplication : No active profile set, falling back to default profiles: default
users-mysql_1 | 2020-04-15 19:48:30.179 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
users-mysql_1 | 2020-04-15 19:48:30.307 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 111ms. Found 1 JPA repository interfaces.
users-mysql_1 | 2020-04-15 19:48:32.111 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8086 (http)
users-mysql_1 | 2020-04-15 19:48:32.196 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
users-mysql_1 | 2020-04-15 19:48:32.197 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33]
users-mysql_1 | 2020-04-15 19:48:32.458 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
users-mysql_1 | 2020-04-15 19:48:32.458 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4509 ms
users-mysql_1 | 2020-04-15 19:48:33.101 INFO 1 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
users-mysql_1 | 2020-04-15 19:48:33.421 INFO 1 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
users-mysql_1 | 2020-04-15 19:48:34.120 INFO 1 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
users-mysql_1 | 2020-04-15 19:48:34.459 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
users-mysql_1 | 2020-04-15 19:48:36.213 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
users-mysql_1 | 2020-04-15 19:48:36.315 INFO 1 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
docker-mysql | mbind: Operation not permitted
users-mysql_1 | 2020-04-15 19:48:37.913 INFO 1 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
users-mysql_1 | 2020-04-15 19:48:37.922 INFO 1 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
users-mysql_1 | 2020-04-15 19:48:38.501 WARN 1 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
users-mysql_1 | 2020-04-15 19:48:38.714 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
users-mysql_1 | 2020-04-15 19:48:39.063 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8086 (http) with context path ''
users-mysql_1 | 2020-04-15 19:48:39.066 INFO 1 --- [ main] r.a.d.DockerMysqlSpringBootApplication : Started DockerMysqlSpringBootApplication in 13.634 seconds (JVM running for 26.846)

spring boot mysql application issues using docker compose

OS details
Mint version 19,
Code name : Tara,
PackageBase : Ubuntu Bionic
Cinnamon (64-bit)
I followed this URL to install mysql 5.7 and workbench 6.3
I can check mysql service running
xxxxxxxxx:~$ sudo netstat -nlpt | grep 3306
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 1547/mysqld
I also checked bind-address inside file: mysqld.cnf under directory : /etc/mysql/mysql.conf.d/
bind-address = 127.0.0.1
I have written a simple spring application using mysql
Here are all classes written
SpringBootDataJpaExampleApplication
#EnableJpaRepositories(basePackages = "com.springbootdev.examples.repository")
#SpringBootApplication
public class SpringBootDataJpaExampleApplication
{
public static void main(String[] args) {
SpringApplication.run(SpringBootDataJpaExampleApplication.class, args);
}
}
UserController
#RestController
#RequestMapping("/api")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping("/create")
public List<User> users() {
User users = new User();
users.setId(new Long(1));
users.setName("Sam");
users.setCountry("Development");
userRepository.save(users);
return userRepository.findAll();
}
#GetMapping("/users")
public List<User> findAll()
{
return userRepository.findAll();
}
}
UserRepository
public interface UserRepository extends JpaRepository<User, Long>
{
}
User
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String country;
//getters and setters
}
partial pom.xml file. Please see I am using spring boot 1.5.9 and jdk 1.8
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
application.properties
spring.datasource.url = jdbc:mysql://mysql-standalone:3306/test
spring.datasource.username = testuser
spring.datasource.password = testpassword
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = create
Dockerfile
FROM openjdk:8
VOLUME /tmp
EXPOSE 8080
ADD target/spring-boot-app.jar spring-boot-app.jar
ENTRYPOINT ["java","-jar","spring-boot-app.jar"]
When I run this application locally using IDE it works fine and I can access:
http://localhost:8080/api/users/
and http://localhost:8080/api/create/
I build image out of my application using command
docker build . -t spring-boot-app
I can see image is being built.
xxxxxxxxxx:$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
spring-boot-app latest 069e53a7c389 27 minutes ago 652MB
mysql 5.7 1b30b36ae96a 8 days ago 372MB
Now I run Command to run the mysql container
docker run --name mysql-standalone -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=test -e MYSQL_USER=testuser -e MYSQL_PASSWORD=testpassword -d mysql:5.7
Then I connect to mysql-standalone container from my application(spring-boot-app) (referencing this)
docker run --name spring-boot-app-container --link mysql-standalone:mysql -d spring-boot-app
With this, I can see my application working fine from docker using
http://(docker-container-ip):8080/api/users/ and http://(docker-container-ip):8080/api/create/
Here I wanted to make the same thing work with docker-compose.
Referenced this to install docker compose.
xxxxxxxxxx:~$ docker-compose --version
docker-compose version 1.22.0, build f46880fe
Then I created file docker-compose.yml in my project directory.
version: '3'
services:
mysql-docker-container:
image: mysql:5.7
environment:
- MYSQL_ROOT_PASSWORD=adminpassword
- MYSQL_DATABASE=test
- MYSQL_USER=testuser
- MYSQL_PASSWORD=testpassword
volumes:
- /data/mysql
spring-boot-app-container:
image: spring-boot-app
build:
context: .
dockerfile: Dockerfile
depends_on:
- mysql-docker-container
ports:
- 8087:8080
volumes:
- /data/spring-boot-app
Changed one line in my application.properties and commented earlier datasource url as below.
spring.datasource.url = jdbc:mysql://mysql-docker-container:3306/test
#spring.datasource.url = jdbc:mysql://mysql-standalone:3306/test
Did clean install so new target jar gets created. I also deleted images and containers from docker.
Then ran below command:
docker-compose up
This is what I see in logs
Creating spring-boot-data-jpa-mysql-docker-no-composer-master_mysql-docker-container_1 ... done
Creating spring-boot-data-jpa-mysql-docker-no-composer-master_spring-boot-app-container_1 ... done
Attaching to spring-boot-data-jpa-mysql-docker-no-composer-master_mysql-docker-container_1, spring-boot-data-jpa-mysql-docker-no-composer-master_spring-boot-app-container_1
spring-boot-app-container_1 |
spring-boot-app-container_1 | . ____ _ __ _ _
spring-boot-app-container_1 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
spring-boot-app-container_1 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
spring-boot-app-container_1 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
spring-boot-app-container_1 | ' |____| .__|_| |_|_| |_\__, | / / / /
spring-boot-app-container_1 | =========|_|==============|___/=/_/_/_/
spring-boot-app-container_1 | :: Spring Boot :: (v1.5.9.RELEASE)
spring-boot-app-container_1 |
spring-boot-app-container_1 | 2018-10-26 01:24:48.748 INFO 1 --- [ main] .s.e.SpringBootDataJpaExampleApplication : Starting SpringBootDataJpaExampleApplication v0.0.1-SNAPSHOT on 582c035536e4 with PID 1 (/spring-boot-app.jar started by root in /)
spring-boot-app-container_1 | 2018-10-26 01:24:48.752 INFO 1 --- [ main] .s.e.SpringBootDataJpaExampleApplication : No active profile set, falling back to default profiles: default
spring-boot-app-container_1 | 2018-10-26 01:24:48.875 INFO 1 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#28c97a5: startup date [Fri Oct 26 01:24:48 UTC 2018]; root of context hierarchy
spring-boot-app-container_1 | 2018-10-26 01:24:51.022 INFO 1 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
spring-boot-app-container_1 | 2018-10-26 01:24:51.063 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
spring-boot-app-container_1 | 2018-10-26 01:24:51.065 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
spring-boot-app-container_1 | 2018-10-26 01:24:51.218 INFO 1 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
spring-boot-app-container_1 | 2018-10-26 01:24:51.218 INFO 1 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2399 ms
spring-boot-app-container_1 | 2018-10-26 01:24:51.335 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
spring-boot-app-container_1 | 2018-10-26 01:24:51.340 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
spring-boot-app-container_1 | 2018-10-26 01:24:51.341 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
spring-boot-app-container_1 | 2018-10-26 01:24:51.341 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
spring-boot-app-container_1 | 2018-10-26 01:24:51.341 INFO 1 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
spring-boot-app-container_1 | 2018-10-26 01:24:51.895 ERROR 1 --- [ main] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
spring-boot-app-container_1 |
spring-boot-app-container_1 | com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
spring-boot-app-container_1 |
spring-boot-app-container_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-app-container_1 | at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_181]
How to fix this error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
I can see lot of answers on this forum for this similar error message. Tried bunch of those options/answers, but that didn't work.
No answer talks about this combination (linux + spring boot + mysql + docker compose)
Note: This has worked fine without using docker-compose. Have already mentioned the same in above description. Am I making any mistake in docker-compose file or application properties file?
I did see lot of people posting about adding hikari dependency in pom.xml if you are using any spring-boot version < 2.0
<!-- Spring Boot Data 2.0 includes HikariCP by default -->
<!-- <dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.1.0</version>
</dependency> -->
With that I thought of using same application but made changes to my pom.xml as below
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
Then I followed exact same things as mentioned in description of issue. With that I saw bit more clear error as below:
spring-boot-app-container_1 | 2018-10-27 18:51:47.259 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
spring-boot-app-container_1 | 2018-10-27 18:51:48.464 ERROR 1 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
spring-boot-app-container_1 |
spring-boot-app-container_1 | com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
spring-boot-app-container_1 |
spring-boot-app-container_1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
That confirms spring-boot 2.0 uses hikari datasource default.
Now coming back to how I solved the issue.
I changed connection string in application.properties like below:
spring.datasource.url = jdbc:mysql://mysql-docker-container:3306/test?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useSSL=false
instead of earlier used:
spring.datasource.url = jdbc:mysql://mysql-docker-container:3306/test
The answer was simple. Below change worked for me in Spring-boot 2.0 as well as Spring-boot 1.5.9: (Add this to your connection string)
?autoReconnect=true&failOverReadOnly=false&maxReconnects=10
Some handy commands:
Once containers are up, you can check ip addresses of containers using command:
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
========================================
UPDATE: some additional handy information...
Below is DEPRECATED
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
This needs to be replaced by
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
To fix HikariCP Pool initialization issue/exception, please set HikariCP’s initializationFailTimeout property to 0 (zero), or a negative number.
# HikaryCP Properties
spring.datasource.hikari.initialization-fail-timeout=0
This property controls whether the pool will "fail fast" if the pool cannot be seeded with an initial connection successfully. Any positive number is taken to be the number of milliseconds to attempt to acquire an initial connection; the application thread will be blocked during this period. If a connection cannot be acquired before this timeout occurs, an exception will be thrown. This timeout is applied after the connectionTimeout period. If the value is zero (0), HikariCP will attempt to obtain and validate a connection. If a connection is obtained, but fails validation, an exception will be thrown and the pool not started. However, if a connection cannot be obtained, the pool will start, but later efforts to obtain a connection may fail. A value less than zero will bypass any initial connection attempt, and the pool will start immediately while trying to obtain connections in the background. Consequently, later efforts to obtain a connection may fail. Default: 1