0

I'm developing a project with Django and I want to use a database to create a dataframe, but I'm stuck with the subject issue (mysql.connector.errors.DatabaseError) 2005 (HY000): Unknown MySQL server host 'db' (8). (Background on this error at: https://sqlalche.me/e/20/4xp6) How should I fix it?

views.py

from sqlalchemy import create_engine, text
def user_detail(req, id):
    engine = create_engine("mysql+mysqlconnector://user:mariadb@db:9051/mariadb")
    query = "SELECT * FROM LoanParcel"
    df = pd.read_sql_query(sql=text(query), con=engine.connect())
    df = df.drop(["id", "date_add", "start_date", "description"], axis = 1)
    return render(req,'pages/user_detail.html')

docker-compose.yml

version: '3.7'
services:
  db:
    image: mariadb:10
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=mariadb
      - MYSQL_DATABASE=mariadb
      - MYSQL_USER=mariadb
      - MYSQL_PASSWORD=mariadb
      - MARIADB_ROOT_PASSWORD=mysecretpassword
    ports:
      - 9051:3306
    volumes:
      - "mysqldata:/var/lib/mysql"  

  web:
    build: .
    restart: always
    command: python manage.py runserver 0.0.0.0:8000
    environment:
      - DATABASE_URL=mysql+mysqlconnector://user:mariadb@db:9051/mariadb
    ports:
      - "9052:8000"
    depends_on:
      - db
      
volumes:
  mysqldata:

docker-compose ps command


NAME                       COMMAND                  SERVICE             STATUS              PORTS
myproject-uborrowu-db-1    "docker-entrypoint.s…"   db                  running             0.0.0.0:3306->3306/tcp
myproject-uborrowu-web-1   "python manage.py ru…"   web                 running             0.0.0.0:8000->8000/tcp
wanx
  • 51
  • 1
  • 4
  • Are you seeing that error from `docker-compose logs web`, or trying to directly run the Python code from your host system or an IDE? Connections between containers don't use `ports:` at all, does using the standard MySQL port 3306 work better? – David Maze Feb 15 '23 at 15:36

1 Answers1

-1

You should add network attribute for yaml file. Containers must be run on same network like that https://docs.docker.com/compose/networking/

enter image description here

++ i found that https://stackoverflow.com/a/71574076/17318894

  • Compose creates a network named `default` for you automatically, and attaches containers to it. For most uses a Compose file should have no `networks:` blocks at all. Also see [Networking in Compose](https://docs.docker.com/compose/networking/) in the Docker documentation. – David Maze Feb 15 '23 at 15:34
  • ([Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) Consider how often you've copy-and-pasted an SO answer; include the YAML content as plain text and not an image file.) – David Maze Feb 15 '23 at 15:35