Yogesh
Yogesh

Reputation: 801

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

Upvotes: 0

Views: 3797

Answers (1)

Facty
Facty

Reputation: 547

docker-compose.yml

version: "3"

services:
  database:
    image: mariadb
    environment:
      MYSQL_ROOT_PASSWORD: maria
    volumes:
      - /my/full/path/sql_scripts:/scripts
      - hyacinth_db:/var/lib/mysql

  web:
    build: /my/full/path/hyacinthBE
    volumes:
      - /my/full/path/hyacinthBE/app:/code
    ports:
      - "8000:80"

volumes:
  hyacinth_db:

conn code:

from fastapi import FastAPI
import mariadb
import sys

app = FastAPI()

try:
    conn = mariadb.connect(
        user="root",
        password="maria",
        host="database",
        port=3306,
        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"}

What I changed and what it do:

  1. You do not have to expose database port to outside of container since only your webapp will be connecting to it
  2. In connection code for app I changed port 3307 -> 3306 since those two containers are at same network no need for running requests outside the stack

Thing here is that using docker internal DNS (containers name) you have to use docker network too thus use default ports exposed by container

Upvotes: 2

Related Questions