Node / GraphQL and Koa: address already in use :::3000

Viewed 74

I am trying to implement GraphQL to my KoaJs server. However, every time nodemon restart on change, I will receive the errors in my console:

Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1334:16)
    at listenInCluster (node:net:1382:12) 
  ...
  code: 'EADDRINUSE',
  errno: -48,
  syscall: 'listen',
  address: '::',
  port: 3000
}
[nodemon] app crashed - waiting for file changes before starting...

Here's my code:

import { ApolloServer, gql } from "apollo-server-koa";
import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
import Koa from "koa";
import http from "http";

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => "Hello world!",
  },
};

async function startApolloServer() {
  const httpServer = http.createServer();
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    csrfPrevention: true,
    cache: "bounded", 
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  });

  await server.start();
  const app = new Koa();
  server.applyMiddleware({ app, path: "/graphql" });
  httpServer.on("request", app.callback());
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 3000 }, resolve)
  );
  console.log(` Server ready at http://localhost:3000${server.graphqlPath}`);
  return { server, app };
}

startApolloServer()

How can I fix the error? Thanks for any help!!

1 Answers

I think you are trying to run on a port that is being used by another service or the same service in the background.

You can try:

  1. You can find the service running on port 3000 and turn it off.

  2. You can change the port you are using. For example, 5000.

To find service:

Windows:

netstat -ano -p tcp | find "3000"

Linux or MacOS

lsof -iTCP -sTCP:LISTEN -n -P | grep :3000

Kill service using the pid. Then run your server again.

Related