🔥
Firebase EmulatorをDockerで立ち上げる
firebase.json
を定義
firebase.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"storage": {
"rules": "storage.rules"
},
"emulators": {
"singleProjectMode": true,
"firestore": {
"port": 8080,
"host": "0.0.0.0"
},
"ui": {
"enabled": true,
"host": "0.0.0.0"
},
"storage": {
"port": 9199,
"host": "0.0.0.0"
},
"auth": {
"port": 9099,
"host": "0.0.0.0"
}
}
}
現状ホスト名を"0.0.0.0"
に設定しないとローカルからコンテナに接続できない。
本番と開発環境のアプリイニシャライザを切り分ける
firebaseAppSingleton
import { FirebaseApp, initializeApp } from "firebase/app";
import { Auth, connectAuthEmulator, getAuth } from "firebase/auth";
import {
connectFirestoreEmulator,
Firestore,
getFirestore,
} from "firebase/firestore";
import {
connectStorageEmulator,
FirebaseStorage,
getStorage,
} from "firebase/storage";
export class FirebaseSingleton {
private static instance: FirebaseSingleton;
private app: FirebaseApp;
private storage: FirebaseStorage;
private db: Firestore;
private auth: Auth;
private constructor(config: FirebaseConfig = firebaseConfig) {
this.app = initializeApp(config);
if (process.env.NODE_ENV === "development") { //💡 開発環境の場合
console.info("Using Firebase Emulator");
const db = getFirestore();
const storage = getStorage();
const auth = getAuth();
// 💡 Firestore, CloudStorage, Firebase Authそれぞれ initialize
connectFirestoreEmulator(db, "127.0.0.1", 8080);
connectStorageEmulator(storage, "127.0.0.1", 9199);
connectAuthEmulator(auth, "http://127.0.0.1:9099", {
disableWarnings: true, //💡 Warningを消す
});
this.db = db;
this.storage = storage;
this.auth = auth;
} else {
//💡 以下は本番系
this.storage = getStorage(this.app);
this.db = getFirestore(this.app);
this.auth = getAuth(this.app);
}
}
....
以下の通りにDockerfile
を作成
Dockerfile
FROM node:20-bullseye-slim
RUN apt update -y && apt install -y openjdk-11-jdk bash
RUN npm install -g firebase-tools
RUN apt-get update && apt-get install -y procps
COPY . .
ENTRYPOINT ["firebase", "emulators:start"]
必要となる jdk と firebase-tools でコンテナの環境構築します
立ちあげやすくするためにdocker compose
ファイルを作成します
docker.compose.yml
version: "1"
services:
firebase-emulators:
volumes:
- database:/database/firebase
container_name: firebase-emulators
build:
context: ../../
dockerfile: docker/firebase-docker/Dockerfile
ports:
- 8080:8080 # FIRESTORE_PORT
- 4000:4000 # UI_PORT
- 9199:9199 # STORAGE_PORT
- 9099:9099 # AUTH_PORT
volumes:
database:
立ち上げ用の npm スクリプトを用意
package.json
"emulators:up": "cd docker/firebase-docker && docker-compose up -d",
"emulators:down": "cd docker/firebase-docker && docker-compose down",
エミュレーターの UI はlocalhost:4000
で確認できます。
Discussion