Reputation: 31
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)
Upvotes: 0
Views: 9445
Reputation: 32294
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'
}
Upvotes: 3
Reputation: 4010
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
Upvotes: 0