Nodejs connect mysql socket to another host?

4.3k views Asked by At

Hello below is my Nodejs code is working fine into my local computer.

var client = mysql.createClient({
    user: '(your user here)',
    password: '(your password here)',
    host: '127.0.0.1',
    port: '3306',
    _socket: '/var/run/mysqld/mysqld.sock',
});

but how can i write the path of "_socket" when i connect with another server. my database located into another lan server and my server ip is 192.168.12.166. how can connect mysql into this server.

Thanks

3

There are 3 answers

0
robertklep On BEST ANSWER

Remove the (undocumented?) _socket option and change the host value:

var client = mysql.createClient({
    user: '(your user here)',
    password: '(your password here)',
    host: '192.168.12.166',
    port: '3306'
});

However, this assumes that the MySQL database on 192.168.12.166 is configured to accept TCP connections (see the answer to this question on how to do that).

0
winmutt On

When you connect to another server, you do not use a local unix socket. The other server should be listening on 3306, you can check that with

netstat -anp|grep LISTEN|grep 3306

It should show a specific IP its listening on (not 127.0.0.1) or 0.0.0.0 for all bound IPs.

1
Faraz Ahmad On

I know it's a bit old thread. If someone only knows has the socket, but not the port (for example, WP Local). This is how you can connect

var client = mysql.createClient({
    user: '(your user here)',
    password: '(your password here)',
    host: '(your database host)',
    port: '(path to your socket file)'
});

That is, pass the path to your socket file to the PORT key. I have tested this in Node v14 using the knex query builder.