Docker NodeJS app connection problem to host monero-wallet-rpc

Solution for Docker NodeJS app connection problem to host monero-wallet-rpc
is Given Below:

Docker NodeJS app connection problem to host monero-wallet-rpc with monero-javascript

I can’t connect to my localhost running monero-wallet-rpc from my NodeJS Docker container. I don’t know where the error comes from. I looked hours into it. Please help.

Before dockerization everything worked fine.

Error:

The console.error(err); in my Monero connection file prints an empty array: []. This proofs there is an error in the try statement. I guess it has to do with the docker networking. However, I can be wrong.

System:

up to date Debian 10
Docker version 20.10.7, build f0df350
docker-compose version 1.29.2, build 5becea4c

docker-compose:

version: "3.8"
services:
  app:
    build: .
    env_file:
      - .env
    command: ["npm", "start"]
    restart: always
    ports:
      - 80:3000
    external_links:
      - mongo
    extra_hosts:
      - "host.docker.internal:host-gateway"

  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    volumes:
      - ./mongodb/data:/data/db
    env_file:
      - .env

  mongo-seed:
    build: ./mongo-seed/.
    links:
      - mongo

volumes:
  db-data:
    name: mongodb

NodeJS Monero connection (monero-javascript):

const monerojs = require("monero-javascript");

const moneroWalletRPCConnect = async () => {
  try {
    const moneroWalletRPC = await monerojs.connectToWalletRpc(
      process.env.MONERO_WALLET_RPC_URI,
      process.env.MONERO_WALLET_RPC_USER,
      process.env.MONERO_WALLET_RPC_PASSWORD
    );
    console.log(
      `MoneroWalletRPC connected to: ${process.env.MONERO_WALLET_RPC_URI}`
    );
    await moneroWalletRPC.openWallet(
      process.env.MONERO_WALLET_USER,
      process.env.MONERO_WALLET_PASSWORD
    );
    console.log(
      `MoneroWallet "${process.env.MONERO_WALLET_USER}" successfully opened.`
    );
    return await moneroWalletRPC;
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
};

module.exports = moneroWalletRPCConnect;

.env file:

MONERO_WALLET_RPC_URI = "http://host.docker.internal:38083"
MONERO_WALLET_RPC_USER = "rpc_user"
MONERO_WALLET_RPC_PASSWORD = "abc123"
MONERO_WALLET_USER = "test"
MONERO_WALLET_PASSWORD = "123"

Monero commands:

monerod --stagenet

monero-wallet-rpc --stagenet --daemon-address http://127.0.0.1:38081 --rpc-bind-port 38083 --rpc-login rpc_user:abc123 --wallet-dir .

Inside nodejs container:

[email protected]:/usr/src/app# cat /etc/hosts 
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.1      host.docker.internal
172.18.0.2      45d96a2fc103
[email protected]:/usr/src/app# getent hosts host.docker.internal
172.17.0.1      host.docker.internal