Blockchain listener app exited with code 0 docker

Viewed 41

I have a simple websocket application running. I use ethers.js to listen to blockchain events, which uses websockets in the background. I connect to blockchain via Infura provider. When I dockerize the app and run the image, it continues to live for about 3-5 minutes, but then exits with code 0 without any errors or messages. When I run the application without dockerizing it from the terminal with simply npx ts-node src/index.ts command, then there is no problem and it keeps running forever.

It also logs ⛓️ [chain]: Started listening events in the docker logs so it is started successfully as well.

No event is captured from the listener and nothing happens, so it is not the case that something is executed and caused it to exit somehow. Also when I am able to make the transaction quick before it exits, it captures the event successfully and continues for some more time as well.

What could be reason behind this and what should I do to keep it running?

Here is my Dockerfile:

FROM node:alpine

WORKDIR /app

COPY package.json .

RUN npm install

COPY . .

CMD ["npx", "ts-node", "src/index.ts"]

Here is my index.ts:

import { listenContractEvents } from './events';

listenContractEvents()
  .then(() => console.log('⛓️ [chain]: Started listening events'))
  .catch(console.log);

Here is my events.ts:

const provider = new ethers.providers.WebSocketProvider(
  `wss://goerli.infura.io/ws/v3/${process.env.INFURA_API_KEY}`
);

async function listenContractEvents() {
  const contract = new ethers.Contract(
    contractAddress,
    contractAbi,
    provider
  );

  let userList: User[] = await contract.getUserList();

  contract.on('Register', async () => {
    console.log('⛓️ [chain]: New user registered!');
    userList = await contract.getUserList();
  });
}
1 Answers

It seems like the problem was with the Infura closing the WebSocket after certain amount of idle time, and since there was no other process running except the WebSockets, the docker container was closing itself considering the job as done.

I have used the following piece of code to restart the websocket every time it closes:

provider._websocket.onclose = () => {
  listenContractEvents();
};
Related