skip to Main Content

I have a problem with my connection between my flask app using flask-sqlalchemy and my database container, i want to make a compose project.
I’m currently using Python3 Flask and MySQL as my database, im trying to connect both containers into a network but i just cant them to get connect.
Need to add that if i run my code locally, just using my editor it works perfectly connecting to my db container, the problem is when i want to create and use my project container.

This is my URI:
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+mysqlconnector://{db_user}:{db_psw}@{db_host}:{db_port}/{db_schema}?connect_timeout=60'

Here are my env vars, i already have loaded them with dotenv:

database_host = 'db'
database_port = 3308
database_user = 'root'
database_psw = 'toor'
database_schema = 'db_news'

My docker-compose.yml:

version: '3'
services:
  db:
    container_name: mysqldb
    image: mysql:8.0.33
    ports:
      - "3308:3306"
    environment:
      MYSQL_DATABASE: db_news
      MYSQL_ROOT_PASSWORD: toor
    volumes:
      - database_data:/var/lib/mysql
    networks:
      - default

  app:
    container_name: app
    build: .
    ports:
      - "5000:4000"
    links:
      - db
    volumes:
      - .:/app
    networks:
      - default

volumes:
  database_data:

networks:
  default:
    driver: bridge

And finally my dockerfile:

FROM python:3.11

WORKDIR /app

COPY . /app

COPY .env .env

RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 4000

CMD ["python3", "app/app.py"]


I have tried changing the port, using ‘localhost’ as host but nothing seems to work.

2

Answers


  1. Chosen as BEST ANSWER

    My docker-compose.yml updated

    services:
      db:
        container_name: mysqldb
        image: mysql:8.0.33
        ports:
          - "3308:3306"
        environment:
          MYSQL_DATABASE: db_news
          MYSQL_ROOT_PASSWORD: toor
        volumes:
          - database_data:/var/lib/mysql
    
      app:
        env_file:
          - .env
        container_name: app
        build: .
        ports:
          - "5000:4000"
     
    volumes:
      database_data:
    

  2. Please confirm if this is correct?

    database_host = 'db'
    database_port = 3306 # not 3308
    database_user = 'root'
    database_psw = 'toor'
    database_schema = 'db_news'
    

    =====================================

    Rebuild Image

    docker compose rm # remove container
    docker compose build # rebuild image
    docker compose up
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search