简体   繁体   中英

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. It works fine and I can use MySQL from my Spring Boot application, when I run Spring Boot application locally (without Docker). 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

In my Spring Boot application.properties I have this configuration:

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:

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:

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

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. My MySQL was running on 172.17.0.2 and 3306 port the default one:

spring.datasource.url=jdbc:mysql://172.17.0.2:3306/mydb 

You can also connect to the MySQL server using any client. I generally use the mysql-client :

sudo  mysql -uroot -pyour_password_here -h 172.17.0.2 -P 3306

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM