0

I am creating a docker file that contains a flask app and mysql. This should run on localhost for now.

The flask app is running and so as the mysql server. I am able to connect to mysql server. The app is not able to connect to db.

Python code connecting

def establish_connection():
    config = {
        'user': 'root',
        'password': 'root',
        'host': '127.0.0.1',
        'port': '3306',
        'database': 'persist'
    }

    cnx: str = mysql.connector.connect(**config)
    print(cnx)
    return cnx

Dockerfile

FROM python:3.7.4-buster
WORKDIR /stocksite
ENV FLASK_APP main.py
ENV FLASK_RUN_HOST 0.0.0.0
EXPOSE 5000 32000 3306
COPY . .
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]

docker-compose.yml

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"

  db:
    image: mysql
    container_name: db
    ports:
      - "32000:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./data/db:/docker-entrypoint-initdb.d

I receive the below error:

mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

ktr.rtk
  • 31
  • 1
  • 2
  • 1
    You need to set "db" as the hostname for the database, since it's running inside a docker container as well. The container_name acts as the hostname in these cases – Tom Aug 25 '19 at 02:29

2 Answers2

3

Docker compose services are available to other services using their name. Your db service can be connected to from your web container using db:3306

config = {
    'user': 'root',
    'password': 'root',
    'host': 'db',
    'port': '3306',
    'database': 'persist'
}
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
0

In the docker-compose you map the port 3306 of the db inside the container to the port 32000 on the host machine.

In the app you should use port 32000 not 3306.

def establish_connection():
config = {
    'user': 'root',
    'password': 'root',
    'host': '127.0.0.1',
    'port': '32000',
    'database': 'persist'
}

cnx: str = mysql.connector.connect(**config)
print(cnx)
return cnx
Tarek Essam
  • 3,602
  • 2
  • 12
  • 21