0

Trying to connect my node app to mysql database. I already have an express api set up that manages to connect but for some reason node doesn't work. Using "links" in the docker compose file, and it resolves to the right local (internal) container IP but still doesn't connect. Error: The node app isn't listening on any ports itself (does it need to?). Thanks!

Error: connect ECONNREFUSED 192.168.64.2:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '192.168.64.2',
  port: 3306,
  fatal: true
}

let con;

async function create_connection() {

const username = await process.env.USERNAME;
const password = await process.env.PASSWORD;
con = await mysql.createConnection({
  host: "db",
  user: username,
  password: password,
  database: "database",
  port: "3306",
});

await con.connect(function(err) {
  if (err) throw err;
});
}

create_connection();

docker-compose:

version: '3.8'
services:
  db:
    image: mysql:8.0.31
    cap_add:
      - SYS_NICE
    restart: always
    env_file:
           - somefile.env
    ports:
            - 127.0.0.1:external_port:3306
    volumes:
      - db:/var/lib/mysql
      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql

  express:
        image: express/someapi
        links:
                - db:db
        ports:
                - 127.0.0.1:external_port:3355
        env_file:
                - somefile.env
        depends_on:
                - db
  node_app:
        image: some_image
        links:
                - db:db
        env_file:
                - somefile.env
        depends_on:
                - db

volumes:
  db:
    driver: local

~

Tried using links and mysql2 to connect to the database. Expected it to work as with my express backend but does not connect.

3
  • 1
    Instead of giving IP, you can provide docker hostname as a host and share your docker-compose file to elaborate more. Commented Jan 27, 2023 at 9:58
  • @NajmusSakib added the docker compose now!
    – W red
    Commented Jan 27, 2023 at 10:04
  • On the port section, you can just connect your port without the host part(simply 3306:3306) docs.docker.com/compose/compose-file/#ports Commented Jan 27, 2023 at 10:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.