介紹

圖片來源
Supabase 是一個開源的後端即服務(BaaS)平台,有內建 PostgreSQL 資料庫,提供即時的 WebSocket 支持和完整的用戶身份認證系統,能夠透過網頁 dashboard 來操作與管理資料庫,並透過內建自動生成 CRUD API 來對資料庫進行操作。

Self-hosting with Docker

事前準備

確保您的主機有以下套件:

  • Docker
  • Git
  • openssl

創建目錄

1
2
cd ~
mkdir -p container/supabase

Clone 專案

1
git clone --depth 1 https://github.com/supabase/supabase

--depth: 只取得該 Git 倉庫的最新一次提交 (commit),而不是克隆完整的歷史記錄,減少下載的數據量,提高速度。

複製 compose 檔案與環境設定檔

1
cp -rf supabase/docker/* container/supabase && cp supabase/docker/.env.example container/supabase/.env && rm -rf supabase

可以根據所需,自行修改 ENV 設定檔內容。

修改環境設定檔

1
2
cd container/supabase
vi .env

預設內容如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
############
# Secrets
# YOU MUST CHANGE THESE BEFORE GOING INTO PRODUCTION
############

POSTGRES_PASSWORD=your-super-secret-and-long-postgres-password
JWT_SECRET=your-super-secret-jwt-token-with-at-least-32-characters-long
ANON_KEY=your-anon-key
SERVICE_ROLE_KEY=your-service-role-key
DASHBOARD_USERNAME=supabase
DASHBOARD_PASSWORD=this_password_is_insecure_and_should_be_updated
SECRET_KEY_BASE=your-secret-key-base
VAULT_ENC_KEY=your-encryption-key-32-chars-min
PG_META_CRYPTO_KEY=your-encryption-key-32-chars-min


############
# Database - You can change these to any PostgreSQL database that has logical replication enabled.
############

POSTGRES_HOST=db
POSTGRES_DB=postgres
POSTGRES_PORT=5432
# default user is postgres


############
# Supavisor -- Database pooler
############
# Port Supavisor listens on for transaction pooling connections
POOLER_PROXY_PORT_TRANSACTION=6543
# Maximum number of PostgreSQL connections Supavisor opens per pool
POOLER_DEFAULT_POOL_SIZE=20
# Maximum number of client connections Supavisor accepts per pool
POOLER_MAX_CLIENT_CONN=100
# Unique tenant identifier
POOLER_TENANT_ID=your-tenant-id
# Pool size for internal metadata storage used by Supavisor
# This is separate from client connections and used only by Supavisor itself
POOLER_DB_POOL_SIZE=5


############
# API Proxy - Configuration for the Kong Reverse proxy.
############

KONG_HTTP_PORT=8000
KONG_HTTPS_PORT=8443


############
# API - Configuration for PostgREST.
############

PGRST_DB_SCHEMAS=public,storage,graphql_public


############
# Auth - Configuration for the GoTrue authentication server.
############

## General
SITE_URL=http://localhost:3000
ADDITIONAL_REDIRECT_URLS=
JWT_EXPIRY=3600
DISABLE_SIGNUP=false
API_EXTERNAL_URL=http://localhost:8000

## Mailer Config
MAILER_URLPATHS_CONFIRMATION="/auth/v1/verify"
MAILER_URLPATHS_INVITE="/auth/v1/verify"
MAILER_URLPATHS_RECOVERY="/auth/v1/verify"
MAILER_URLPATHS_EMAIL_CHANGE="/auth/v1/verify"

## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=false
SMTP_ADMIN_EMAIL=admin@example.com
SMTP_HOST=supabase-mail
SMTP_PORT=2500
SMTP_USER=fake_mail_user
SMTP_PASS=fake_mail_password
SMTP_SENDER_NAME=fake_sender
ENABLE_ANONYMOUS_USERS=false

## Phone auth
ENABLE_PHONE_SIGNUP=true
ENABLE_PHONE_AUTOCONFIRM=true


############
# Studio - Configuration for the Dashboard
############

STUDIO_DEFAULT_ORGANIZATION=Default Organization
STUDIO_DEFAULT_PROJECT=Default Project

# replace if you intend to use Studio outside of localhost
SUPABASE_PUBLIC_URL=http://localhost:8000

# Enable webp support
IMGPROXY_ENABLE_WEBP_DETECTION=true

# Add your OpenAI API key to enable SQL Editor Assistant
OPENAI_API_KEY=


############
# Functions - Configuration for Functions
############
# NOTE: VERIFY_JWT applies to all functions. Per-function VERIFY_JWT is not supported yet.
FUNCTIONS_VERIFY_JWT=false


############
# Logs - Configuration for Analytics
# Please refer to https://supabase.com/docs/reference/self-hosting-analytics/introduction
############

# Change vector.toml sinks to reflect this change
# these cannot be the same value
LOGFLARE_PUBLIC_ACCESS_TOKEN=your-super-secret-and-long-logflare-key-public
LOGFLARE_PRIVATE_ACCESS_TOKEN=your-super-secret-and-long-logflare-key-private

# Docker socket location - this value will differ depending on your OS
DOCKER_SOCKET_LOCATION=/var/run/docker.sock

# Google Cloud Project details
GOOGLE_PROJECT_ID=GOOGLE_PROJECT_ID
GOOGLE_PROJECT_NUMBER=GOOGLE_PROJECT_NUMBER

生成 SECRET

JWT_SECRET & SECRET_KEY_BASE & VAULT_ENC_KEY & PG_META_CRYPTO_KEY 這四個環境變數請使用以下命令分別生成。

1
openssl rand -base64 32

生成完畢後請到 .env 裡修改。

重要環境變數說明

  • JWT_SECRET: 用於身份驗證。
  • POSTGRES_PASSWORD: 資料庫密碼。
  • POSTGRES_PORT: 資料庫連接埠。

修改 compose.yml

1
vi docker-compose.yml

修改 docker-compose.yml,把 supavisor 的 5432 埠號註解。

1
2
3
4
5
6
7
supavisor:
container_name: supabase-pooler
image: supabase/supavisor:2.7.4
restart: unless-stopped
ports:
#- ${POSTGRES_PORT}:5432
- ${POOLER_PROXY_PORT_TRANSACTION}:6543

開放 db 的 5432 埠號,方便我們後續連結資料庫。

1
2
3
4
5
6
db:
container_name: supabase-db
image: supabase/postgres:15.8.1.085
restart: unless-stopped
ports:
- ${POSTGRES_PORT}:5432

啟動服務

1
docker compose up -d

查看服務

1
docker compose ps

重點服務介紹:

  • PostgreSQL: 資料庫服務。
  • PostgREST: 資料庫自動生成的 REST API。
  • Storage: 檔案儲存服務。
  • Kong: API Gateway。
  • Supabase Studio: 網頁管理界面。

進入 Supabase Dashboard

打開瀏覽器並輸入 <your ip>:8000,輸入剛剛在 env 檔設定的 Dashboard 帳密即可登入。

如何連線到資料庫

點擊 Dashboard 上的 connect 按鈕即可查看連線方式

選擇您的連線方式進行連線測試。

建立資料表

創建一個新的 Table,並新增 nameage 欄位,如下圖設定。

按下 Save 儲存按鈕,即可看到我們創建的學生資料表。

接下來我們就可以對這張 Table 進行 CRUD 了。

連接範例:Python

Supabase 有提供多項內建 Client API 進行連接

我們使用 Python 來對資料庫進行 CRUD。

詳細內容可以參考 Supabase Python Docs

事前準備

確保您的主機有以下套件:

  • Docker
  • Devcontainer

初始開發環境設定

Devcontainer.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"name": "PythonSandbox (Ubuntu)",
"image": "mcr.microsoft.com/devcontainers/base:jammy",
"features": {
"ghcr.io/va-h/devcontainers-features/uv:1": {}
},
"customizations": {
"vscode": {
"extensions": ["donjayamanne.python-extension-pack"]
}
},
"runArgs": ["--network=host"],
"remoteUser": "vscode"
}
1
2
3
mkdir supabase-test && cd supabase-test
uv init .
uv add supabase dotenv

Init Connection

在專案根目錄中創建 .env 檔案,並輸入以下內容。

1
2
SUPABASE_URL="your supabase url"
SUPABASE_KEY="your supabase key"

為了後續方便做資料庫操作,SUPABASE_KEY 請設定為 SERVICE_ROLE_KEY

1
2
3
4
5
6
7
8
import dotenv
from supabase import create_client, Client

dotenv.load_dotenv()

url: str = dotenv.get_key("SUPABASE_URL")
key: str = dotenv.get_key("SUPABASE_KEY")
supabase: Client = create_client(url, key)

Create

1
2
3
4
5
6
response = (
supabase.schema("public")
.table("student")
.insert({"id": 1, "name": "Bob", "age": 20})
.execute()
)

Supabase 自架或官方的 PostgREST 只會暴露三個 schema 給 API 使用。

  • public: 主要資料表存放的地方
  • storage: 給 Supabase Storage API 使用
  • graphql_public: 給 GraphQL API 使用

Read

1
2
3
4
5
6
response = (
supabase.schema("public")
.table("student")
.select("*")
.execute()
)

Update

1
2
3
4
5
6
7
response = (
supabase.schema("public")
.table("student")
.update({"name": "Alice"})
.eq("id", 1)
.execute()
)

Delete

1
2
3
4
5
6
7
response = (
supabase.schema("public")
.table("student")
.delete()
.eq("id", 1)
.execute()
)