Help me connect api container to mysql container?

Having a real hard time connecting my dockered fastapi with mysql db. There are so many youtube videos that I’ve tried to copy and I feel i’m really close. The api works, but when i try to query i get:

pythonapp-1  | mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on 'mysql:8809' (111)

these are my files

docker-compose.yaml:

services:
  pythonapp:
    build: ./python/
    ports:
      - '8000:8000'
    command: sh -c "sleep 60s ; uvicorn hello_world:app --reload --host 0.0.0.0 --port 8000"
    depends_on:
      - mysql


  mysql:
    build: ./mysql/
    restart: always
    environment:
      MYSQL_DATABASE: 'db'
      MYSQL_ROOT_PASSWORD: 'root'
    ports:
      - '8809:8809'

dockerfile:

FROM python:3.11.8

RUN pip install mysql-connector-python fastapi dataclasses uvicorn

WORKDIR /usr/app/src

COPY hello_world.py ./

EXPOSE 8000

CMD ["uvicorn", "hello_world:app", "--reload", "--host",  "0.0.0.0", "--port", "8000"] 

dockerfile:

FROM mysql:latest 

COPY ./tpl_database.sql /docker-entrypoint-initdb.d/

Python script

hello_world.py:

import mysql.connector
from fastapi import FastAPI
from dataclasses import dataclass
import uvicorn


app = FastAPI()

def get_data(*args, database='tplabs_db', **kwarg):


    db_connection = mysql.connector.connect(
        user='root', password='root', host='mysql', port='8809', database='db') #ändra localhost till mysql sen)
    print(f"Connected to: {database}")

    cursor = db_connection.cursor()

    if kwarg:
        cursor.execute(kwarg['query'])

    else:
        cursor.execute(args[0])

    data_list = cursor.fetchall()

    db_connection.close()
    db_columns = next(zip(*cursor.description))

    db = [{db_columns[idx]: value for idx, value in enumerate(person)} for person in data_list]


    return db

appreciate any help!


Please, format your post according to the following guide: How to format your forum posts
In short: please, use </> button to share codes, terminal outputs, error messages or anything that can contain special characters which would be interpreted by the MarkDown filter. Use the preview feature to make sure your text is formatted as you would expect it and check your post after you have sent it so you can still fix it.

Example code block:

```
echo "I am a code."
echo "An athletic one, and I wanna run."
```

bro can u help me atleast?

Since you do build your own mysql image, can you show us where/how you make the service listen on port 8809?

It must be either in the Dockerfile, or you must modify the default port somewhere in your entrypoint script, or copy a cnf inside the container that takes care of binding to port 8809 instead of 3306.

the code you see is all the code i have, besides the sql queries.

1 x yaml
2 x dockerfiles, in case you missed both
1 x python

what am i missing ?

Indeed, I missed the Dockerfile for the mysql database.

Based on the questions I asked, you should already understand what the issue is: you expect mysql to run on container port 8809, without actually configuring it to run on container port 8809.

Always use the container ports as described in the image description, unless you understand how to make the process inside the container bind a different port.

thats the thing, I thought i had already configured it here

mysql:
    build: ./mysql/
    restart: always
    environment:
      MYSQL_DATABASE: 'db'
      MYSQL_ROOT_PASSWORD: 'root'
    ports:
      - '8809:8809'

so how should I do it instead?

I fail to see how/where you configured it. Are you referring to the right side of the published port as “I had already configured it”?

  ports:
      - '8809:8809'

that part in the yaml is where i thought i had configured it, how would you configure it?

What you configured just creates a port forwarding rule from a host port to a container port, regardless whether something actually listens on that container port or not. Note: Docker doesn’t care what process is running inside the container, and has no idea how to configure every existing or future application.

I have no idea how to configure mysql to listen on a different port. Though, the image description or mysql documentation should point out how it needs to be done.

Though, why don’t you just use the default port like described in the image description: 3306. You need to fix it in your port mapping '8809:3306` and fix it in your python code.

yo this forum is worthless

@pook46 I think your behavior is inappropriate.
Here in the forum, many people are trying their best to help you. These people spend their free time to help, and for that you can be truly grateful. If an answer does not meet your requirements, you can point this out in an appropriate manner.

As @meyay said, you can change the port to 3306, because MySQL normally starts with this default port.

Alternatively you can change the port of MySQL to 8809.
I’ll even give you a link on how to do that without having to search for it yourself.

2 Likes

It’s working now thanks to you and this forum.

Forgive me for lashing out. I have learned my lesson to be patient.