Home > Blockchain >  Node.js able to connect to MySQL container when app is ran locally but unable to connect when app is
Node.js able to connect to MySQL container when app is ran locally but unable to connect when app is

Time:12-02

Docker-Compose file:

version: '3.8'

networks:
  app-tier:
    driver: bridge


services: 
  mysql_node: 
    image: mysql:5.7
    restart: always
    environment: 
      MYSQL_DATABASE: 'sample_db' 
      MYSQL_USER: 'user' 
      MYSQL_PASSWORD: 'password' 
      MYSQL_ROOT_PASSWORD: 'password'
    ports: 
      - '3306:3306'
    expose: 
      - '3306' 
    volumes:
      - mysql_db:/var/lib/mysql
  app:   
    depends_on:
      - mysql_node
    build: .   
    ports:
      - 3000:3000
    environment:
      - MYSQL_HOST=mysql_node
      - MYSQL_USER=root
      - MYSQL_PASSWORD=password
      - MYSQL_NAME=sample_db
      - MYSQL_PORT=3306
      - MYSQL_HOST_IP=mysql_node
    networks:
      - app-tier   
    volumes:
      - .:/app

volumes:
  mysql_db:

docker file:

FROM node:latest

RUN mkdir app

WORKDIR /app

COPY . .  
RUN npm install

EXPOSE 3000

CMD ["node", "app.js"]

Sourcecode:

const http = require('http')
var mysql = require('mysql');


const hostname = '0.0.0.0'
const port = 3000

console.log(process.env.MYSQL_HOST_IP)
console.log(process.env.MYSQL_PORT)
var con = mysql.createConnection({
  host: "process.env.MYSQL_HOST_IP",
  user: "user",
  password: "password",
  port: 3306
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
}); 

When I run docker-compose up the MySQL container successfully launches. But the app exits, with error code Error: connect ETIMEDOUT.

When I run the app locally via node app.js I end up getting a successful "Connected!" message output to my console.

I'm able to connect to the database via MySQLWorkbench as well. It's just the app is unable to connect to the db when the app is ran as a container.

CodePudding user response:

You've specified that the app should be on a named network and the database shouldn't. Then the database service goes on the default network and the two containers can't talk to each other.

I'd remove the named network from the app, since it's probably not needed.

  app:   
    depends_on:
      - mysql_node
    build: .   
    ports:
      - 3000:3000
    environment:
      - MYSQL_HOST=mysql_node
      - MYSQL_USER=root
      - MYSQL_PASSWORD=password
      - MYSQL_NAME=sample_db
      - MYSQL_PORT=3306
      - MYSQL_HOST_IP=mysql_node
    volumes:
      - .:/app
  • Related