Issue
I have a docker container which is based on a springboot project and generated with this command :
docker run --net=host -d --restart unless-stopped -v /home/ramses/dockerTest:/uploads/deployment --name ramses-bl2 abyster01/ramses-bl2:528
but the container does not access to my database, as you can see in this error :
Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
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.
My container is launched in host mod, and i verified the root (the user i set in my springboot project properties) is set as user in my database as you can see in this screenshots :
Finally i test connection to my database successfully with the same credentials as in my properties. But i don't know why i'm getting this error.
Solution
I would recommend for you to use a docker-compose.yml
file. Add to the file the following:
version: '3'
services:
mysql-standalone:
image: mysql:latest
environment:
- MYSQL_ROOT_PASSWORD=***
- MYSQL_DATABASE=***
- MYSQL_USER=***
- MYSQL_PASSWORD=**
volumes:
- data:/var/lib/mysql
spring-boot:
image: *your-app-name-image*
ports:
[8080:8080]
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mysql-standalone
volumes:
data:
Then in the application.properties
have the following configuration
server.port=8080
spring.datasource.url=jdbc:mysql://<container-name>:3306/<db-name>
spring.datasource.username=***
spring.datasource.password=***
Finally, run docker-compose up
.
Note that one of the differences between docker run versus docker-compose is that docker-compose reads configuration data from a YAML file instead of having to set your configuration from a cli
Answered By - Roland
Answer Checked By - Senaida (JavaFixing Volunteer)