Connect to a mysql server running in a docker container from another container?
Solution 1
Ohh, my good luck.
It's working now. I rebuilt the docker image and connected to the database with the IP that I found with inspect mysql
container, and with port 32031
.
Run docker container same as: $ docker run -p 3000:3000 --network mynetwork node-server node index.js
var pool = mysql.createPool({
connectionLimit : 3,
host : '172.18.0.1',
user : 'root',
port : 32031,
password : 'abc123',
database : 'mydatabase',
charset : 'utf8mb4',
timezone : 'PKT',
timeout : 4000
});
Solution 2
Docker containers connected via a network can communicate internally. Your mysql container is running on port 3306
internally and 32031
externally.
Try connecting via port 3306
. It should work.
Solution 3
If you connect by IP which you get from docker inspect command
. That mean your connection now is 172.18.0.2
and port still 3306
Another way to connect from nodejs (nodejs and mysql in same network). Connect information is:
hostname: mysql // container name
port: 3306
Related videos on Youtube
Basit
Updated on June 04, 2022Comments
-
Basit almost 2 years
I have two containers; a node.js server, and a mysql server ...
Both are running fine, I'm trying to connect to the database running in the MySQL container from my node app.
I've created a bridge network:
$ docker network create -d bridge mynetwork
and run both of my containers in this network with:
$ docker run -p 32031:3306 --network mynetwork --name mysql -e MYSQL_ROOT_PASSWORD=abc123 -d mysql:5.7 $ docker run -p 3000:3000 --network mynetwork node-server node index.js
I'm trying to connect with the IP of the mysql container that I found with
docker inspect mysql
, which is172.18.0.2
and port32031
.Where did it go wrong, it's not connecting?
-
Žilvinas Jocius about 5 yearsCan you write the results of docker stats when both containers are up? Do you expose 32031 port in dockerfile?
-
-
David Maze about 5 yearsThat IP address will change whenever the container gets recreated; I'd recommend never looking up or using the container-internal IP addresses. The host name approach is much more reliable.
-
Truong Dang about 5 yearsThat right, host name by container name is the right way. And thay how docker-compose use