如何通过应用程序容器连接mysql容器的localhost:3306-docker [英] How to connect localhost:3306 of mysql container via app container- docker

查看:359
本文介绍了如何通过应用程序容器连接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

现在我有两个容器App和mysql。我已经链接了两个容器

Now I have two container App and mysql. I have linked both container

docker run --name app --link mysql:dbalias appimage

,但是我收到通讯链接失败错误。我无法连接mysql服务器

but I am getting Communications link failure error. I am not able to connect with mysql server

我使用以下命令运行mysql容器:

I used below command to run mysql container:

docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d -p 3306:3306 mysql:latest

有任何建议吗?

推荐答案

您要指向 localhost ,这表示该应用正在尝试连接到其自己容器的 localhost 。不是主机的本地主机。

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

spring.datasource.url=jdbc:mysql://mysql:3306/gosallowMultiQueries=true&createDatabaseIfNotExist=true

如果它们不是'您可以使用mysql容器的容器IP,但是当容器重新启动/重新创建时,它可以更改。推荐的方法是创建用户定义的桥接网络:

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

当两个容器都在同一用户定义的网络内启动时,您可以使用容器名称进行通信(可以由 docker exec 在其中一个容器内并尝试使用容器nam对另一个容器执行ping操作e)。

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

这篇关于如何通过应用程序容器连接mysql容器的localhost:3306-docker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆