[英]Running Spring Boot app inside Docker container, unable to connect MySQL
I'm trying to learn Docker and I created a container which is running MySQL server.我正在尝试学习 Docker,并创建了一个运行 MySQL 服务器的容器。 It works fine and I can use MySQL from my Spring Boot application, when I run Spring Boot application locally (without Docker).
它工作正常,当我在本地运行 Spring Boot 应用程序(没有 Docker)时,我可以从我的 Spring Boot 应用程序中使用 MySQL。 But when I try to run Spring Boot application inside another Docker container, connection to MySQL fails and I get error:
java.net.ConnectException: Connection refused
但是,当我尝试在另一个 Docker 容器中运行 Spring Boot 应用程序时,与 MySQL 的连接失败并出现错误:
java.net.ConnectException: Connection refused
In my Spring Boot application.properties
I have this configuration:在我的 Spring Boot
application.properties
我有这样的配置:
spring.datasource.url: jdbc:mysql://127.0.0.1/mydb
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver
Any ideas what might be wrong?任何想法可能有什么问题?
When you want to use the MySQL container from your Spring Boot container a good idea would be to link to it like:当您想使用 Spring Boot 容器中的 MySQL 容器时,一个好主意是链接到它,例如:
docker run ... --name spring-boot --link mysql ...
Assuming that mysql is the name of your MySQL container you could then use the following JDBC URL in your configuration:假设mysql是您的 MySQL 容器的名称,那么您可以在配置中使用以下 JDBC URL:
spring.datasource.url: jdbc:mysql://mysql/mydb
The best way to handle this situation (which I used) would be to run your MySQL container in detached mode.处理这种情况(我使用过)的最佳方法是以分离模式运行 MySQL 容器。 Obviously, you can name your container as you like:
显然,您可以随意命名容器:
docker run --detach --name = my-MySQL --env = "MYSQL_ROOT_PASSWORD=your_password_here" mysql
Your container will be running in detached mode, now you can check the IP and the port on which its running using the inspect command :您的容器将在分离模式下运行,现在您可以使用检查命令检查运行它的 IP 和端口:
docker inspect docker_mysql
And you can check the logs using:-您可以使用以下方法检查日志:-
docker logs my-MySQL
Furthur you can use the IP you get after inspecting.此外,您可以使用检查后获得的 IP。 My MySQL was running on 172.17.0.2 and 3306 port the default one:
我的 MySQL 在 172.17.0.2 和 3306 端口上运行,这是默认的:
spring.datasource.url=jdbc:mysql://172.17.0.2:3306/mydb
You can also connect to the MySQL server using any client.您还可以使用任何客户端连接到 MySQL 服务器。 I generally use the mysql-client :
我通常使用mysql-client :
sudo mysql -uroot -pyour_password_here -h 172.17.0.2 -P 3306
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.