Issues with MySQL Connection Between Docker Instances
I’ve set up a MySQL database using Docker with the following 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 am attempting to connect to this MySQL instance using a Python script. The connection code is as follows:
host='127.0.0.1'
port=3306
user='root'
password='5895'
mysql.connector.connect(
host=host,
port=port,
user=user,
password=password,
database=your_database_name
)
This connection works when I execute the Python script locally; however, I want to run this script inside another Docker container.
Dockerfile for the Python Application
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
When I build my Docker image using:
docker build -t twitter-alpha . --no-cache
And then run it with:
docker run -itd -p 3000:3000 --name test --network mynetwork twitter-alpha
I encounter the following error:
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (99)
I discovered that replacing 127.0.0.1 with the container’s IP address obtained from:
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id
fixes the issue, but I’m concerned about relying on the changing IP address each time the container is restarted. What’s the best practice for maintaining a reliable connection?