Swatcat
Swatcat

Reputation: 55

Cannot connect to MySQL (python MySql-Connector) when in docker container

I have a Python Flask based app that needs to connect to a database

version: "3.7"

networks:
  localdev:
    driver: bridge

services:
  sysman-db:
    image: mysql:8.0
    container_name: sysman-db
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    ports:
      - "4000:3306"
    environment:
      MYSQL_ROOT_PASSWORD: xxxxx
    volumes:
      - ./database/docker:/etc/mysql/conf.d
      - ./database/schema.sql:/docker-entrypoint-initdb.d/dump0.sql
    networks:
      - localdev

  sysman:
    build:
      context: .
      dockerfile: Dockerfile.sysman
    container_name: sysman
    depends_on:
      - sysman-db
    ports:
      - "3030:3030"
    networks:
      - localdev
    links:
      - lsm-db

The Flask application connects to the MySql, it has a retry method because of Docker bringing up sysman before the database initialisation completes.

Even when the database is up, I am still getting:

sysman    | 2020-02-11 13:55:08 [ERROR] Unable to connect to db, reason: 2003: Can't connect to MySQL server on 'sysman-db:4000' (111 Connection refused)
sysman    | 2020-02-11 13:55:18 [ERROR] Unable to connect to db, reason: 2003: Can't connect to MySQL server on 'sysman-db:4000' (111 Connection refused)
sysman    | 2020-02-11 13:55:28 [ERROR] Unable to connect to db, reason: 2003: Can't connect to MySQL server on 'sysman-db:4000' (111 Connection refused)
sysman    | 2020-02-11 13:55:38 [ERROR] Unable to connect to db, reason: 2003: Can't connect to MySQL server on 'sysman-db:4000' (111 Connection refused)

The database connect is:

dbConfig = { 'host' : '127.0.0.1', 'port' : 4000, 'user' : user, 
             'password' : password, 'database' : database }
connPool = mysql.connector.pooling.MySQLConnectionPool(pool_name='myPool',
                                                       pool_size=3,
                                                       pool_reset_session=True,
                                                       **dbConfig)

If I bring up the MySql container on its own then using mysql -u root -p -P 4000 I can connect.

Upvotes: 0

Views: 2013

Answers (2)

aekiratli
aekiratli

Reputation: 538

You are trying to connect the localhost of the flask container which does not run mysqld. 4000 port counts for published port. 2 containers should talk via 3306 port

Try this:

dbConfig = { 'host' : 'sysman-db', 'port' : 3306, 'user' : user, 
             'password' : password, 'database' : database }

Upvotes: 0

Mihai
Mihai

Reputation: 10757

Your sysman container should connect to the database container using sysman-db:3306 (not 4000). Remember that it is communication between 2 services so the published ports don't count.

Upvotes: 1

Related Questions