dockerdocker-compose

Cannot connect to mysql in 2 database containers docker-compose setup


I have docker-compose setup with 2 databases and 2 phpmyadmins. First one works fine, but I have problems connecting to second one (mysql_logs). When I open phpmyadmin2 (localhost:8081) it says it cannot connect to database:

Cannot connect: invalid settings.

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

docker-compose.yml:


services:
  mysql_logs:
    image: mysql:5.6
    restart: on-failure
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: logs
    ports:
      - '3307:3306'

  mysql:
    image: mysql:5.6
    restart: on-failure
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: app
    ports:
      - '3306:3306'

  nginx:
    image: nginx:1.19.0-alpine
    restart: on-failure
    volumes:
      - './public/:/usr/src/app'
      - './docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro'
    ports:
      - '80:80'
    depends_on:
      - php

  php:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    volumes:
      - './:/usr/src/app'
    depends_on:
      - mysql

  phpmyadmin:
    image: phpmyadmin
    restart: always
    ports:
      - 8080:80
    environment:
      - PMA_HOST=mysql
      - PMA_PORT=3306
      - PMA_USER=root
      - PMA_PASSWORD=root

  phpmyadmin2:
    image: phpmyadmin
    restart: always
    ports:
      - 8081:80
    environment:
      - PMA_HOST=mysql_logs
      - PMA_PORT=3307
      - PMA_USER=root
      - PMA_PASSWORD=root

Solution

  • In phpmyadmin2.environment, you defined PMA_PORT=3007 because you were trying to connect to mysql_logs which is the second database, right?

    And because you did

    services:
      mysql_logs:
        ports:
          - '3307:3306'
    

    you thought mysql_logs was exposed on port 3307, right?

    Well, there resides the issue. mysql_logs is published on port 3307, but only for the host machine. For the other services defined in services, its still exposed on port 3306.

    So to fix that, in phpmyadmin2.environment, you need to define PMA_PORT=3006