メモインフラFirebase

ポートが使用されていてFirebaseエミュレータが起動できない時の対処法

2021.05.31

こんにちはjunです、最近Firebaseを使用したアプリケーション開発をしています。エミュレータがあるのでそこでFirestoreやAuthenticationのテストをしています。ある日、開発の続きをやろうとしてエミュレータを起動させました。

firebase emulators:start

しかし

⚠  firestore: Port 8081 is not open on localhost, could not start Firestore Emulator.
⚠  firestore: To select a different host/port, specify that host/port in a firebase.json config file:
      {
        // ...
        "emulators": {
          "firestore": {
            "host": "HOST",
            "port": "PORT"
          }
        }
      }
i  emulators: Shutting down emulators.

Error: Could not start Firestore Emulator, port taken.

あらら、、起動に失敗してしまいました。エミュレーター二回目の起動の時によく発生します。原因はCould not start Firestore Emulator, port taken.とある様にポートが使用中だからです。

firebase.jsonにはエミュレーターのポートを定義できます。私の場合は以下の通りです。

"emulators": {
    "auth": {
        "port": 9099
    },
    "functions": {
        "port": 5001
    },
    "firestore": {
        "port": 8081
    },
    "database": {
        "port": 8082
    },
    "ui": {
        "enabled": true
    }
},

とりあえず8081と8082でどんなプロセスが動いているか確かめましょう。(この時はfirestoreだけでなくdatabaseも取られていました。)

Macで任意ポートで使用されているプロセスを調べる時は以下の様なコマンドを打ちます。

lsof -i:PORT

なので今回は

lsof -i:8081
OMMAND  PID       USER   FD   TYPE            DEVICE SIZE/OFF NODE NAME
java    2322       jun   93u  IPv6 0x3f5922436f29fd5      0t0  TCP localhost:sunproxyadmin (LISTEN)

なんだろう?とりえずエミュレーター系だと思う。なのでこのプロセスをkillする

kill 2322

そしてもう一度起動

firebase emulators:start
┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4002                │
└─────────────────────────────────────────────────────────────┘

OK!これで起動完了。以上がFirestore、Databaseでポートが取られて起動できない時の対処法です。Authとかは起きないのに、なぜかfirestoreとDatabaseだけ発生します。。