'Drupal cannot access MySQL Docker container

This is relevant for Drupal 8.9.3, MySQL 5.7 and Docker (with docker-compose.yml) file. Specifically on the Drupal Install step "Set up database", Drupal throws out error [Failed to connect to your database server. The server reports the following message: SQLSTATE[HY000] [2002] Connection refused] when I try to connect using Host: 127.0.0.1.

Database name: Hub2
Database username: drupal
Database password: drupal
Host: 127.0.0.1
Port number: 9403 (This is because of resever proxy used / so on purpose not 3306)

If I used hostmachine IP address (e.g. 192.168.2.122) then it works fine, with same settings for Database name, database username, database password and also port number.

I am using DBeaver to work and look at the DBs and DBeaver can connect to mysql container using 127.0.0.1 using same user as above (in the Drupal install).

My docker-compose.yml file below:

    version: '3.8'
services:
  hub_db:
    image: mysql:5.7     
    container_name: hub_db
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: hub2
      MYSQL_USER: drupal
      MYSQL_PASSWORD: drupal
      MYSQL_ROOT_HOST: 127.0.0.1
    volumes:
      - ./mysql/data:/var/lib/mysql   
      - ./mysql/mysql_logs:/var/log/mysql
      - ./mysql/configuration/my.cnf:/etc/my.cnf
    # Traefik port settings
    ports:
     - "9403:3306"
    networks:
      dev_local_mysql:
    # Traefik label settings
    labels:
      - traefik.enable=true
      - traefik.docker.network=dev_local_mysql
      - traefik.tcp.routers.hub_db.entrypoints=mysql
      - traefik.tcp.routers.hub_db.tls=true
      - traefik.tcp.services.hub_db.loadbalancer.server.port=9403
networks:
  dev_local_mysql:
    name: dev_local

My my.cnf file below:

[mysqld]
port=3306
max_connections=250
#bind-address=127.0.0.1
max_allowed_packet=1073741824 
[client]
port=3306

Drupal_install, image link
DBeaver_successfulconnection, image link



Sources

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

Source: Stack Overflow

Solution Source