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 6 monthsI 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 mynetworkand 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.jsI'm trying to connect with the IP of the mysql container that I found with
docker inspect mysql, which is172.18.0.2and port32031.Where did it go wrong, it's not connecting?
-
Žilvinas Jocius almost 4 yearsCan you write the results of docker stats when both containers are up? Do you expose 32031 port in dockerfile?
-
-
David Maze almost 4 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 over 3 yearsThat right, host name by container name is the right way. And thay how docker-compose use