5

Before, I created named volume and database: 'mysql-db1' using other mysql container.

I can't connect to database from python.

My .yml file :

    version: '3.6'

    services: 
      python:
        image: python:latest
        ports:
         - '80:80'
        volumes:
          - type: bind
            source: .
            target: /scripts
        command: tail -f /dev/null
        links:
          - 'mysql'

      mysql:
        image: mysql/mysql-server:latest
        ports:
         - '3306:3306'
        environment:
          MYSQL_ROOT_PASSWORD: root
        volumes:
          - type: volume
            source: mysql-db1
            target: /var/lib/mysql


    volumes: 
      mysql-db1:
        external: true

My simply python code:

    import mysql.connector

    cnx = mysql.connector.connect(user='root', password='root', host='mysql', database='test1')
    cnx.close()

I can enter the database using:

    $ docker-compose exec mysql bash
    # mysql -uroot -proot -Dtest1

Error:

    mysql.connector.errors.DatabaseError: 1130 (HY000): Host '172.18.0.3' is not allowed to connect to this MySQL server

Where is a problem?

LubieCiastka
  • 143
  • 1
  • 3
  • 9
  • 1
    https://github.com/docker-library/mysql/issues/275 This (what lucile-sticky commented on Apr 6, 2017) might help you. It can be a permission problem either because of the volume, or because the IP is simply not allowed (like the error says). – Teemu Risikko Jul 05 '18 at 12:56
  • You need to define the environment `MYSQL_DATABASE=test`, so that the database exists when the container starts – Tarun Lalwani Jul 05 '18 at 13:09
  • 1
    looks like worth trying: https://stackoverflow.com/questions/1559955/host-xxx-xx-xxx-xxx-is-not-allowed-to-connect-to-this-mysql-server – trust512 Jul 05 '18 at 13:32

1 Answers1

7

root user is not allowed to access the db externally by default. Use image environment variables to create a user and use that:

db:
restart: always
image: mariadb
container_name: myapp_db
environment:
  - MYSQL_USER=myuser
  - MYSQL_PASSWORD=mypass
  - MYSQL_DATABASE=mydb
  - MYSQL_ALLOW_EMPTY_PASSWORD=yes
ports:
  - 3306:3306
Dmitrii G.
  • 895
  • 1
  • 7
  • 21
  • Thanks, it was problem with root user. Adding this variable the user has not been created. I had to do it manually, but that's probably because I already use the created named volume. Do I think right ? – LubieCiastka Jul 05 '18 at 21:08
  • I think right. I had to do it manually, that's because I'm using the previously created named volumes. Initialization step will be skipped. – LubieCiastka Jul 05 '18 at 21:19
  • Or put the env variables an ".env" file and import it into `env_file: - myfile.env`. – questionto42 Jan 05 '22 at 10:10