In my application setting I am connecting to db with below settings
spring.jpa.hibernate.ddl-auto=none
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/gosallowMultiQueries=true&createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
Now I have two container App and mysql. I have linked both container
docker run --name app --link mysql:dbalias appimage
but I am getting Communications link failure error. I am not able to connect with mysql server
I used below command to run mysql container:
docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d -p 3306:3306 mysql:latest
Any suggestion?
解决方案
You are pointing to localhost which means the app is trying to connect to localhost of it's own container. NOT the localhost of your host.
If those 2 containers are deployed inside the same user defined bridge network you can can communicate using container names:
spring.datasource.url=jdbc:mysql://mysql:3306/gosallowMultiQueries=true&createDatabaseIfNotExist=true
if they aren't you can use the container IP of the mysql container but this can change when the container restarts/is recreated. The recommended approach is to create a user defined bridge network:
$ docker network create my-network
$ docker network ls
NETWORK ID NAME DRIVER SCOPE
73df63463bb2 bridge bridge local
4cabe965c01d host host local
c94ae182d8fa my-network bridge local
93ec6f5bf028 none null local
and start your two containers inside the same network:
$ docker run --name mysql --network=my-network -e MYSQL_ROOT_PASSWORD=root -d -p 3306:3306 mysql:latest
When both containers are started inside the same user defined network you can communicate using container name (you can test by docker exec inside one of the containers and try to ping the other one using the container name).