2

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 is 172.18.0.2 and port 32031.

Where did it go wrong, it's not connecting?

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
Basit
  • 862
  • 1
  • 12
  • 30

3 Answers3

4

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
Truong Dang
  • 3,119
  • 1
  • 15
  • 21
  • 1
    That 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. – David Maze Feb 27 '19 at 11:07
  • That right, host name by container name is the right way. And thay how docker-compose use – Truong Dang Feb 27 '19 at 13:54
3

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.

Manish Dash
  • 2,004
  • 10
  • 20
3

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
});
J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
Basit
  • 862
  • 1
  • 12
  • 30