DB connection issue when using internal hostnames

I’m deploying a simple webapp composed by a webserver and a mysql db.
I placed the services in the same network and I verified I can ping the db container from the webserver container using the container name as hostname (meaning networking is setup correctly).

But then if I try to use the container name as hostname in the db connection string I get an error like

ERROR 2003 (HY000): Can't connect to MySQL server on 'db' (111)

If I keep everything the same but use external ip of the machine (let’s say as hostname, the connection works fine.

I tried with both the service name (db) and conatiner_name (my_db) and they all ping fine but won’t connect. So I suspect is some mysql access policy. But shouldn’t this be the deault usage (via internal hostname) and therefore supported by default?

Here is a simple dockerfile to replicate ( I replaced my webapp by another sql image a run a mysql command to try the connection)

version: "3.5"

    image: mysql:latest
    restart: always
    - db
    - my-network
    command: mysql --host=db --user=root --password=mypassword --port=3308 --execute="show databases;"

    image: mysql:latest
    container_name: my_db
    command: --default-authentication-plugin=mysql_native_password
    restart: always
      MYSQL_ROOT_PASSWORD: mypassword
      - ~/docker-services/my_webapp/db_data:/var/lib/mysql
      - 3308:3306
      - my-network

    name: my-network
    driver: bridge


LOL I think I solved it just after creating this.
The solution as suspected was to set

bind-address =

in /etc/mysql/my.cnf

I still wonder why this is not by default in the mysql docker image.

Remove ‘–port=3308’ and don’t publish any ports from service ‘db’. The connection should go directly from service ‘test’ to ‘db’ (on port 3306), not to the port published on the Docker host.

Edit: And you don’t have to create any networks manually, docker-compose will do this for you.

1 Like

You were absolutely right. I was using the external port instead of internal one. Damn! thank you