Docker Community Forums

Share and learn in the Docker community.

Cant connect to Mysql on a container

Hello,

Im now trying to connect to mysql DB but i get this error

ERROR 1045 (28000): Access denied for user ‘magento’@‘localhost’ (using password: YES)

I dont know what or where the problem is

this is the docker-compose I made

version: '2'
services:
  mysql:
    image: 'mysql:8.0.22'
    container_name: mysql
    environment:
      - MYSQL_DATABASE= magentodb
      - MYSQL_ROOT_PASSWORD= my-secret-pw
      - MYSQL_USER= magento
      - MYSQL_PASSWORD= my-secret-pw
    ports:
      - '3306:3306'
    volumes:
        - mysql-vol:/var/lib/mysql

  elasticsearch:
    image: 'elasticsearch:7.10.1'
    container_name: elasticsearch
    environment:
      - node.name=elasticsearch
      - discovery.type=single-node
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - elasticsearch-vol:/usr/share/elasticsearch/data
    ports:
      - '9200:9200'

  magento:
    build: .
    container_name: magento
    ports:
      - '80:80'
      - '443:443'
    depends_on:
      - mysql
      - elasticsearch

volumes:
  elasticsearch-vol:
    driver: local
  mysql-vol:
    driver: local

my question is, why I cant connect to mysql while I defined the mysql user and password as env. variables when creating the container?

Your mysql container exposes port 3306 to its network while it mapps its port 3306 to hosts 3333 port.
When you use the ports property you mapp the port to the localhost, not the other containers on the network.

From inside the web-servercontainer you should be able to connect to the mysql server via mysql -uroot -padmin -h database -P 3306 while from your host you should be able to use mysql -uroot -padmin -h localhost -P 3333.

hello @lewish95,
Thank you a lot for your reply

I just need to know why 3333 port is configured, I didnt configure port 3333 anywhere, I only exposed 3306, is it configured by default or what?

I also found a problem in my docker-compose code, there was a space after the = sign in my env. variables of the mysql container

but after fixing this error, I got a new error.

SQLSTATE[HY000]` [2002] No route to host

In InstallCommand.php line 274:
                               
  Parameter validation failed  

also tried tp connect to the mysql from the mysql container itself but i got access denied, isnt that a little bit strange?