'docker-compose exposed mysql server only accessible via network, not via localhost

I have a simple mysql docker-compose container:

version: "3.8"

services:
  mysql:
    image: mysql:8.0.28-debian
    command: --default-authentication-plugin=mysql_native_password
    ports:
      - "3306:3306"
    volumes:
      - mysql_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: GU.RzstgCNt8E*;]tH5wXZWZHlSk8;<O
    networks:
      - private

networks:
  private:

volumes:
  mysql_data:

After calling docker-compose up -d, I see that my machine is listening:

# sudo netstat -tulpen
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode      PID/Program name
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      0          7249255    12181/docker-proxy

However, trying to connect via telnet 127.0.0.1 3306 will result in a timeout.

From a network machine though, I get a response:

telnet vserver.mydomain.de 3306
Trying 29.98.136.164...
Connected to vserver.mydomain.de.
Escape character is '^]'.
J
8.0.28  OS↑PT☻→=□§^ll^Gl♫9-
rmysql_native_password

After stopping docker via docker-compose stop, also on the network machine gives my a timeout. So I was connecting to the correct address.

Why can't I connect via 127.0.0.1 from the machine hosting the docker container to mysql?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source