Search code examples
pythondockerdocker-composemariadbdocker-network

Python-Docker container cannot connect to MariaDB-Docker container


I'm trying to get my dockerized python-script to get data from an also dockerized mariadb.

I know this should be possible with networks or links. However, due to links being deprecated (According to the Docker documentation), I'd rather not use links.

docker-compose:

version: "3.7"

services:

[...]

 mariadb:
   build: ./db
   container_name: maria_db
   expose: 
     - 3306
   environment:
     MYSQL_ROOT_PASSWORD: root
     MYSQL_USER: user
     MYSQL_PASSWORD: user
   restart: always
   networks:
       - logrun_to_mariadb
[...]

 logrun_engine:
   build: ./logrun_engine
   container_name: logrun_engine
   restart: always
   networks:
     - logrun_to_mariadb

networks:
   logrun_to_mariadb:
       external: false
       name: logrun_to_mariadb

The logrun_engine container executes a python-script on startup:

import mysql.connector as mariadb

class DBConnector:
   def __init__(self, dbname):
       self.mariadb_connection = mariadb.connect(host='mariadb', port='3306', user='root', password='root', database=dbname)
       self.cursor = self.mariadb_connection.cursor()

   def get_Usecases(self):
       self.cursor.execute("SELECT * FROM Test")
       tests = []
       for test in self.cursor:
           print(test) 
       print("Logrun-Engine running...")

test = DBConnector('test_db')
test.get_Usecases()

Whenever I run docker-compose up -d, my logrun_engine logs are full of the error message:

_mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on 'mariadb' (111)

When I run the python script locally and connect to a local mariadb, it works with no problems, so the script should be correct.

Most answers I found concerning this error-message are that the people used localhost or 127.0.0.1 instead of the docker container, which I already have.

I tried with bridged networks, host networks, links etc. but apparently I haven't found the correct thing yet.

Any idea how to connect these two containers?


Solution

  • OK, so I was just too impatient and didn't let mysql start up properly before querying the database, thanks @DanielFarrel for pointing that out. When I added a 10sec delay in the python script before querying the database, it magically worked...