1

I have deployed my docker application (to DigitalOcean). Everything work's, but I can't connect mysql with nodejs.

When I run docker-compose up I get error database.connect is not a function.

My server.js file is look like this

const mysql = require("mysql");

const database = mysql.createPool({
    host: process.env.MYSQL_HOST_IP,
    user: "db_user",
    password: "db_user_pass",
    database: "guess-game",
    port: 3306,
});

database.connect((err) => {
    if (err) {
        console.error("error connecting: " + err.stack);
        return;
    }
    console.log("connected as id " + db.threadId);
});

module.exports = db;

I don't know what I need to write this line to make it work.

host: process.env.MYSQL_HOST_IP,

I tried to add droplet IP as host, but this is also don't work.

host: "http://46.101.162.111/",

Also, I try this.

host: "46.101.162.111",

My docker-compose.yml file

version: "3"

networks:
  dbnet:

services:
  phpmyadmin: 
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin1
    environment: 
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    restart: always
    links:
      - db
    ports: 
      - 8899:80
    depends_on:
      - db
    networks:
      - dbnet

  api:
    build: ./api
    container_name: api1
    command: npm run start
    restart: unless-stopped
    ports:
      - "3005:3005"
    environment: 
      - PORT=3005
      - MYSQL_HOST_IP=172.18.0.2
    depends_on:
      - phpmyadmin
    networks:
      - dbnet

  db: 
    image: mysql:latest
    container_name: db
    command: --default-authentication-plugin=mysql_native_password
    environment:
      - MYSQL_ROOT_PASSWORD=my_secret_password
      - MYSQL_DATABASE=guess-game
      - MYSQL_USER=db_user
      - MYSQL_PASSWORD=db_user_pass
    restart: always
    ports: 
      - 6033:3306
    networks:
      - dbnet

Struggling almost 3 days. 😣

7
  • did you try MYSQL_HOST_IP=db? Commented Feb 10, 2022 at 17:24
  • @Anatoly no I don't Commented Feb 10, 2022 at 17:25
  • @Anatoly This is also won't work Commented Feb 10, 2022 at 17:28
  • Did you try to ping db host from api container? Commented Feb 10, 2022 at 17:32
  • @Anatoly yes I ping. db host is reachable Commented Feb 10, 2022 at 18:24

1 Answer 1

1

You just need to indicate a DB container name instead of IP like this:

MYSQL_HOST_IP=db
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.