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.
CodePudding user response:
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
CodePudding user response:
For what you need it is not necessary to run in host mode. In general you should always avoid doing so.
First of all check the IP address of the host on your local network (not the local interface 127.0.0.1 but something like 192.168.X.X or similar).
Make sure you can access your database from host by connecting to this IP and the correct port. Also check that the user you use can connect also from hosts other than localhost.
Then run the container with the additional flag: --add-host mydatabase:192.168.X.X
. Your application inside the container should use mydatabase
as the database server name.