Ismail Armouti
Ismail Armouti

Reputation: 33

Connecting NodeJS Docker container to a MySQL Docker container - docker-compose 3

When I try to connect two docker containers on the same machine, one running a node.js server and the other running mysql dbms

I get the following error:

(node:32) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND jdbc:mysql://localhost:3306 jdbc:mysql://localhost:3306:3306

mysql driver connection config

const connection= mysql.createConnection({
  host: 'jdbc:mysql://topsectiondb:3306',
  user: 'root',
  password: 'rootpass' 
})

docker-compose.yml

version: '3'
services:
  topsection:
    container_name: topsection-server
    restart: always
    build: .
    ports:
      - '7777:7777'
    depends_on: 
      - topsectiondb
    environment:
      - PORT=7777
  topsectiondb:
    container_name: topsectiondb
    image: mysql:8.0.3
    ports:
      - '3306:3306'
    environment:
      - MYSQL_ROOT_PASSWORD=rootpass

Dockerfile

FROM node:10

RUN mkdir serviceFolder

WORKDIR /usr/app/

COPY . . 

RUN npm install

EXPOSE 7777

CMD ["npm", "start"]

for a more complete stack trace https://gist.github.com/armouti/877a8b4405330c44e4009ebae3df822c

Upvotes: 2

Views: 9142

Answers (1)

mortuie
mortuie

Reputation: 335

First of all there are a couple of problems here.

Firstly you need to look at networking your docker containers in your docker-compose file together. Basically each container doesn't know of the other until you specify which network they are in. Each container can be in multiple but if you want two containers to connect they need to be in the same network. https://docs.docker.com/compose/networking/#configure-the-default-network

Then Secondly you can't use localhost as a url. Basically a docker container is an isolated environment so it has it's own "localhost" so when you use that address it's actually trying to connect to the mysql on the nodejs container. So when networked properly you will be able to connect to the mysql container using their names you gave them in the docker-compose something like topsectiondb:3306 or something like this. This tells docker your using networking to connect one docker container to another and will allow you to make the initial connection. Connect to another container using Docker compose

===================================================

Actual Answer:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

Basically the mysql library requires a hostname, which in most cases is localhost, but as your linking containers with docker-compose you use the alias of the container. The port number is 3306 by default

So: host: "topsectiondb" will suffice!

Upvotes: 5

Related Questions