简体   繁体   中英

How to connect to mySQL docker instance from another docker instance on the same machine

I have setup mySQL through docker using below commands:

  1. docker.network create -d bridge m.network
  2. docker run -p 3306:3306 -.network m.network --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 docker build -t twitter-alpha. --no-cache and startup this docker instance with docker run -itd -p 3000:3000 --name test -.network m.network 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.

Solution was to set host= nameOfDockerInstance

Took me a while

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM