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

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)

Related

Springboot - Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled

I have just created the spring boot application from spring initializer and execute it in intellij.But I am facing some error. Can anyone please help me to solve the error?
package com.demo.grocery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class GroceryApplication {
public static void main(String[] args) {
SpringApplication.run(GroceryApplication.class, args);
}
}
And this is the error I am facing
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.2)
2022-07-29 22:12:46.331 INFO 14136 --- [ main] com.demo.grocery.GroceryApplication : Starting GroceryApplication using Java 11.0.13 on DESKTOP-MQ2O3FR with PID 14136 (C:\Users\keerthi\Downloads\grocery\target\classes started by keerthi in C:\Users\keerthi\Downloads\grocery)
2022-07-29 22:12:46.336 INFO 14136 --- [ main] com.demo.grocery.GroceryApplication : No active profile set, falling back to 1 default profile: "default"
2022-07-29 22:12:47.288 INFO 14136 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-07-29 22:12:47.306 INFO 14136 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 7 ms. Found 0 JPA repository interfaces.
2022-07-29 22:12:48.437 INFO 14136 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-07-29 22:12:48.463 INFO 14136 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-07-29 22:12:48.463 INFO 14136 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-07-29 22:12:48.721 INFO 14136 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-07-29 22:12:48.721 INFO 14136 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2267 ms
2022-07-29 22:12:48.832 WARN 14136 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2022-07-29 22:12:48.839 INFO 14136 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-07-29 22:12:48.868 INFO 14136 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-07-29 22:12:48.897 ERROR 14136 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1
I have tried most of the solutions from stackoverflow, help me to solve this error
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
Paste this in your application properties file in the resource folder.
Change the database name in the second line and also change the username and password according to your database.

"Error: Cannot find module 'mysql2/promise'" when running "docker-compose up"

I want to use docker compose to connect a node program, in one container, to a MySQL database, in another container. The database seems to start fine, but my index.js file throws an error: Cannot find module 'mysql2/promise'
I've tried installing different packages with npm, and even edited various lines in my package.json file in desperation, but to no avail; always the same error. Here are the relevant files, and the output of the commands that work so far.
$ npm install mysql2
npm WARN simplyanything#1.0.0 No repository field.
npm WARN simplyanything#1.0.0 No license field.
+ mysql2#2.3.3
updated 1 package and audited 101 packages in 3.302s
found 0 vulnerabilities
$ sudo npm install mysql2-promise
+ mysql2-promise#0.1.4
updated 1 package and audited 101 packages in 3.772s
found 0 vulnerabilities
package.json
{
"name": "simplyanything",
"version": "1.0.0",
"scripts": {
"start": "node index.js"
},
"description": "Actions party game",
"dependencies": {
"express": "^4.17.1",
"mysql2": "^2.3.3",
"mysql2-promise": "^0.1.4",
"socket.io": "^4.4.1"
},
"author": "Chris DeHaan"
}
index.js
const express = require('express');
let app = express();
let http = require('http').createServer(app);
const io = require('socket.io')(http, {pingTimeout: 60000});
app.use(express.static('public'));
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); });
http.listen(3000, () => { console.log('listening on *:3000'); });
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
connectionLimit : 100,
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
[.... and so on]
Dockerfile
FROM node:latest
WORKDIR /sa/
COPY package.json .
RUN npm install
COPY . .
docker-compose.yml
version: '3.8'
services:
web:
build:
context: .
env_file: ./.env
command: npm start
volumes:
- .:/sa/
- /sa/node_modules
ports:
- $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
depends_on:
- mysqldb
environment:
MYSQL_HOST: mysqldb
mysqldb:
image: mysql
env_file: ./.env
environment:
MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
MYSQL_DATABASE: $MYSQL_DATABASE
ports:
- $MYSQL_LOCAL_PORT:$MYSQL_DOCKER_PORT
volumes:
- mysql:/var/lib/mysql
- mysql_config:/etc/mysql
volumes:
mysql:
mysql_config:
.env
MYSQL_USER=simplyanythingUser
MYSQL_ROOT_PASSWORD=[Well, you don't need to know this]
MYSQL_DATABASE=simplyanything
MYSQL_LOCAL_PORT=3306
MYSQL_DOCKER_PORT=3306
NODE_LOCAL_PORT=3000
NODE_DOCKER_PORT=3000
$ sudo docker build -t sa .
Sending build context to Docker daemon 9.526MB
Step 1/5 : FROM node:latest
---> e6bed6a65a54
Step 2/5 : WORKDIR /sa/
---> Using cache
---> 3da61e5a5928
Step 3/5 : COPY package.json .
---> Using cache
---> 1e7bbeaaa894
Step 4/5 : RUN npm install
---> Using cache
---> 52f36e54d698
Step 5/5 : COPY . .
---> e0a50567567b
Successfully built e0a50567567b
Successfully tagged sa:latest
$ node index.js
Debugger listening on ws://127.0.0.1:44273/a1b49bfc-83e7-47dd-ba53-64a8df19ccc9
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
listening on *:3000
(and it works in the browser at this point)
$ sudo docker-compose up
Starting sa_mysqldb_1 ... done
Starting sa_web_1 ... done
Attaching to sa_mysqldb_1, sa_web_1
mysqldb_1 | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.
mysqldb_1 | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
mysqldb_1 | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.
mysqldb_1 | 2022-02-08T08:31:21.660916Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.28) starting as process 1
mysqldb_1 | 2022-02-08T08:31:21.747461Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
web_1 |
web_1 | > simplyanything#1.0.0 start
web_1 | > node index.js
web_1 |
mysqldb_1 | 2022-02-08T08:31:23.587278Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
web_1 | node:internal/modules/cjs/loader:936
web_1 | throw err;
web_1 | ^
web_1 |
web_1 | Error: Cannot find module 'mysql2/promise'
web_1 | Require stack:
web_1 | - /sa/index.js
web_1 | at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
web_1 | at Function.Module._load (node:internal/modules/cjs/loader:778:27)
web_1 | at Module.require (node:internal/modules/cjs/loader:999:19)
web_1 | at require (node:internal/modules/cjs/helpers:102:18)
web_1 | at Object.<anonymous> (/sa/index.js:13:15)
web_1 | at Module._compile (node:internal/modules/cjs/loader:1097:14)
web_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
web_1 | at Module.load (node:internal/modules/cjs/loader:975:32)
web_1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12)
web_1 | at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
web_1 | code: 'MODULE_NOT_FOUND',
web_1 | requireStack: [ '/sa/index.js' ]
web_1 | }
web_1 |
web_1 | Node.js v17.4.0
mysqldb_1 | 2022-02-08T08:31:25.086275Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysqldb_1 | 2022-02-08T08:31:25.086445Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
mysqldb_1 | 2022-02-08T08:31:25.277625Z 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.
mysqldb_1 | 2022-02-08T08:31:25.354311Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
mysqldb_1 | 2022-02-08T08:31:25.355558Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.28' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
I'm really stuck because everything it needs seems to be installed, and it works when I run it on the command line with node index.js so obviously there's something I'm missing in setting up my container, or getting compose to connect them. Any advice would be much appreciated. Cheers.
Good afternoon, I had the same problem. You could try to use
npm install mysql2

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)

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

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.

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