I have setup mySQL through docker using below commands:
- docker network create -d bridge mynetwork
- docker run -p 3306:3306 --network mynetwork --name mysql -e MYSQL_ROOT_PASSWORD=5895 -d mysql:latest
I'm using a python connector to connect.
host=127.0.0.1
port=3306
user=root
root=5895
mysql.connector.connect(host=host, port=port, user=user, password=password, database=database)
Now this works fine if I run my python file locally (not on docker). Now I want to create a dockerized version.
Dockerfile
FROM python:3.8
WORKDIR /twitter-alpha
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY /constants ./constants
COPY /connectors ./connectors
COPY backfillFollowed.py .
COPY backfillUsers.py .
COPY .env .
RUN apt-get update
RUN apt-get -y install vim
I then build docker instance with docker build -t twitter-alpha . --no-cache
and startup this docker instance with docker run -itd -p 3000:3000 --name test --network mynetwork twitter-alpha
. When I create a docker image for my python files (Dockerfile below) and run the same python script I get mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (99)
If I switch 127.0.0.1 with the IP found from docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' a627c65ddc3c
it works, but this seems like a bad approach since IP will change every time the container is created.