Search code examples
mysqldocker

How to fix "Access denied for user 'root'@'172.22.0.4' (using password: YES)" when connecting to mysql container?


I'm creating a laravel project in a docker container, along with MySQL and phpmyadmin, when trying to migrate (or access the database from phpmyadmin) I get access denied error.

I've tried several SOF solutions but none of them worked, also tried ones in GitHub issues.

here is my docker-compose.yml

version: "3"

services:
  web:
    container_name: ${APP_NAME}_web
    build:
      context: ./docker/web
    ports:
      - 9000:80
    volumes:
      - ./:/var/www/app
    networks:
      - mynet
  db:
    image: mysql:5.7
    container_name: db
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: laracocodb
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - mysqldata:/var/lib/mysql/
    networks:
      - mynet

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: phpma
    links:
      - db:db
    ports:
      - 9191:80
    environment:
      MYSQL_USERNAME: root
      MYSQL_ROOT_PASSWORD: root
      PMA_HOST: db
    networks:
      - mynet
networks:
  mynet:
    driver: bridge
volumes:
  mysqldata:
    driver: local

no matter where I access the database (from db container bash, from phpmyadmin index page or from the web service when trying to migrate the database), the error is always access denied


Solution

  • I have also run into this problem many times, by default MySQL allows root to be accessed by localhost user that means even if you have opened the port 3306:3306, you will still need to add the user.

    Follow these commands and the error will resolve!

    https://stackoverflow.com/a/11225588