How to connect MariaDB and Python in docker

I have two containers: python and mariadb. Since the domain name is the container name in docker i used host as <container_name>, but it fails to connect.

The following is my docker-compose.yaml

version: "3"

services:
  db:
    container_name: mydb
    image: mariadb
    restart: always
    ports:
      - "3307:3306"
    environment:
      MYSQL_ROOT_PASSWORD: maria
    volumes:
      - ./sql_scripts:/scripts
      - hyacinth_db:/var/lib/mysql

  web:
    build: ./hyacinthBE
    container_name: hyacinth
    volumes:
      - ./hyacinthBE/app:/code
    ports:
      - "8000:80"
    depends_on:
      - db
    restart: on-failure

volumes:
  hyacinth_db:

Note: the container_name of mariadb is "mydb", and port is 3307.

My python connection code is as follows:

from fastapi import FastAPI
import mariadb
import sys

app = FastAPI()

try:
    conn = mariadb.connect(
        user="root",
        password="maria",
        host="mydb",
        port=3307,
        database="Hyacinth"
    )
except mariadb.Error as e:
    print(f"Error connecting to MariaDB Platform: {e}")
    sys.exit(1)
cur = conn.cursor()


@app.get("/")
def read_root():
    return {"Hello": "World"}

Docker ps after docker-compose up
enter image description here

Source: Docker Questions

LEAVE A COMMENT