Home > Blockchain >  Docker container is unable to connect to another container through host ip/domain
Docker container is unable to connect to another container through host ip/domain

Time:07-27

I've got following two containers:

mysql - docker run -d -e MYSQL_ROOT_PASSWORD=secretpassword -p 3306:3306 --restart=unless-stopped -v /var/lib/mysql:/var/lib/mysql --name mysql mysql:8.0.29

and springapp with a Spring Boot app which tries to connect to it:

spring.datasource.url=jdbc:mysql://<HOST_IP_ADDRESS>:3306/databaseschema

This ends up in with an error message:

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

I am able to connect to MySQL using MySQL Workbench from my PC without any issues. I was able to fix this connection issue in two ways:

  • adding both containers to the same network and using mysql container name
  • adding spring app to the host network

My question is: Why is the connection not possible? I thought if I can connect to the mysql instance from the "external" world, than it should be also possible from the container. Does someway differentiate if the port is managed by Docker container and then access is restricted for other containers?

CodePudding user response:

By using -p 3306:3306 with your MySQL container you've exposed port 3306 to your host machine which then, in turn, exposes it to other machines on its network (effectively). It doesn't expose it to other containers running on the same machine because containers are meant to be isolated.

Of course you can effectively disable this behaviour by running your spring app container with --network=host.

CodePudding user response:

You can try usign the name of the container, for example:

spring.datasource.url=jdbc:mysql://mysql:3306/databaseschema

If it doen't work try usign the same network for both containers

  • Related