[MongoDB] mongoose DB 연결 시 connect ECONNREFUSED ::1:27017 에러 해결 (feat. IPv6)

Woonil·2025년 12월 7일

MongoDB

목록 보기
1/1

로컬 환경에서 mongoose로 MongoDB 데이터 베이스 서버 연결이 아래와 같은 문구와 함께 실패했다.

connect ECONNREFUSED ::1:27017

이를 해결하기 위해 구글링해서 바로 해결할 수 있었다.

환경변수 설정 파일에 아래와 같이 데이터 베이스 URI를 변경했다.

# localhost -> 127.0.0.1
MONGODB_URI=mongodb://127.0.0.1:27017/vuisiness

하지만 여기서 의문이 생겼다.
아니 127.0.0.1이 localhost의 루프백 주소니까 정상 동작해야 하는거 아닌가?

에러 메시지를 다시 보자!
::1:27017 부분의 ::1127.0.0.1랑 확실히 다른데..

혹시나 IPv6를 나타내는 것이 아닐까 구글링을 다시 해보니 아니나 다를까 IPv6의 루프백 주소인 것을 알게 되었다.

스택오버플로우 - What is IPv6 for localhost and 0.0.0.0?

그렇다면 mongoose는 왜 localhost를 IPv4로 해석하지 못하는가?

This is the minimum needed to connect the myapp database running locally on the default port (27017). For local MongoDB databases, we recommend using 127.0.0.1 instead of localhost. That is because Node.js 18 and up prefer IPv6 addresses, which means, on many machines, Node.js will resolve localhost to the IPv6 address ::1 and Mongoose will be unable to connect, unless the mongodb instance is running with ipv6 enabled.
[출처: mongoose 공식문서]

현재 환경은 Next.js로 결국 node 환경에서 돌아가고 있다.

이를 해결하기 위해서는 아래 두 가지 방법이 있다.

  1. 명시적 IPv4 명시 (위 방법과 동일)
  2. mongoose 연결 family 옵션 명시

2번 방법은 mongoose에서 DB 연결 시 직접적으로 IP 패밀리를 명시할 수 있게 하는 설정이다.

family 옵션
Whether to connect using IPv4 or IPv6. This option passed to Node.js' dns.lookup() function. If you don't specify this option, the MongoDB driver will try IPv6 first and then IPv4 if IPv6 fails. If your mongoose.connect(uri) call takes a long time, try mongoose.connect(uri, { family: 4 })
[출처: mongoose 공식문서]

import mongoose from "mongoose";

const connectDB = async () => {
  if (mongoose.connections[0].readyState) {
    return;
  }
  await mongoose.connect(process.env.MONGODB_URI, {
    family: 4,
  });
};

export default connectDB;
profile
프론트 개발과 클라우드 환경에 관심이 많습니다:)

0개의 댓글