Home > database >  Spring boot dockerized cannot reach MySQL
Spring boot dockerized cannot reach MySQL

Time:10-20

I dockerized a MySQL database by doing:

  1. docker pull mysql
  2. docker run --name=container_name -p 3307:3307 -e MYSQL_ROOT_PASSWORD=password -d mysql

Now the container <container_name> is the only one I have in Docker, and its network is set by default to "bridge".

Using: docker exec -it container_name mysql -u root -p (then typing the password) I created a brand new database.

I tried reaching that database from my SQL client, using the specified credentials and database url:

server: localhost or container_name, port: 3307, user: root, password: password.

The client doesn't reach the database and I get the following errors:

Connection refused: connect

Communications link failure

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

Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

Obviously I get the same error while running my spring boot application (not dockerized yet), but the problem is something in MySQL container since the SQL client isn't working as well.

I've been reading countless questions same as mine, but the solutions that they offer, never work for me.

What's weird is the fact that in the past projects it worked fine.

I'm running Docker on Windows 10 Pro with Hyper-V.

CodePudding user response:

If you're trying to connect from outside of Docker, your docker run -p option is wrong: the second port number always needs to be the standard port number of its service. For MySQL, that second port number needs to be 3306, always. The two port numbers need to match.

docker run -d -p 3307:3306 ... mysql
#                     ^^^^
#                      must be the standard port number

If you're trying to connect from inside Docker, then

  1. You must docker network create a network, and docker run --net all involved containers on that network
  2. You must use the other container's name as a host name, not localhost
  3. You must use the standard port number, again 3306; docker run -p options are ignored (and aren't required)
docker network create some-net
docker run -d --net some-net --name database \
  -p ... -e ... -v ... \
  mysql
docker run -d --net some-net --name application \
  -e MYSQL_HOST=database \
  -e MYSQL_PORT=3306 \
  my/application

If you're running this under Docker Compose, it automatically creates the network for you, and you can use the Compose service name as the host name. You do not need to manually set up networks: or override the container_name:.

version: '3.8'
services:
  database:
    image: mysql
    # ports: [...]
    # environment: [...]
    # volumes: [...]
  application:
    build: .
    environment:
      MYSQL_HOST: database
      MYSQL_PORT: '3306'
  • Related