2

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?

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

If you were not linking both containers, I'd expect the datasource url to be 'jdbc:mysql://<IP of host where both containers are running>/mydb' assuming Spring boot container and MySQL container are running on the same host.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.