docker mysql 3306,如何通过应用程序容器连接mysql容器的localhost:3306-docker

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值