phpMyAdmin mysqli::real_connect(): (HY000/2002): Connection refused

I’m trying to set up a website with a MySQL database, but whenever I try to connect to the database from either Apache or phpMyAdmin it shows mysqli::real_connect(): (HY000/2002): Connection refused.

I can log in and access the database just fine from my host machine using MySQL Workbench, but not from the containers.

Any help would be appreciated, I don’t know what I’m missing or doing wrong.

My compose.yml:

version: '3.9'
services:
  web:
    container_name: website
    image: php:8.0-apache
    restart: unless-stopped
    hostname: web
    domainname: local
    ports:
      - 8080:80
    links:
      - db:db
    volumes:
      - ./html:/var/www/html
    extra_hosts:
      - "database.url.com:127.0.0.1"

  db:
    container_name: database
    image: mysql:latest
    hostname: db
    domainname: local
    restart: unless-stopped
    command: [
      '--authentication-policy=caching_sha2_password'
    ]
    environment:
      MYSQL_ROOT_HOST: "%"
      MYSQL_ROOT_PASSWORD: root_passwd
      MYSQL_DATABASE: db_name
      MYSQL_USER: user_name
      MYSQL_PASSWORD: secret_passwd
    ports:
      - 3306:3306
    volumes:
      - "./mysql/init_test.sql:/docker-entrypoint-initdb.d/init.sql"
      - ./mysql/data:/var/lib/mysql

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    hostname: phpmyadmin
    domainname: local
    container_name: phpmyadmin
    restart: unless-stopped
    links:
      - db:db
    ports:
      - 8081:80
    environment:
      MYSQL_USER: user_name
      MYSQL_PASSWORD: secret_passwd
    extra_hosts:
      - "database.url.com:127.0.0.1"

localhost inside a container, is not the same localhost as on the host or of any other container.

To access the database service db from other containers in the same container network, you need to call the database by its service name db. The extra hosts variables are not required. Furthermore, there is no need to link containers in a user defined network (like the one compose creates for you). It is a legacy configuration item that was required for containers on the default bridge.

1 Like

Thank you so much, this did it.

I did not know that it is possible to use the service name instead of hostname.local to access other containers, like I would when accessing another device on my network.

It also seems that I was using out-dated tutorials, considering the config items I used.