Appwrite:开源后端即服务神器,快速构建Web和移动应用

背景

开发 Web 和移动应用时,后端开发往往是最耗时的部分:

  • 需要搭建用户认证系统
  • 需要设计数据库结构
  • 需要配置文件存储服务
  • 需要开发 API 接口
  • 需要部署和维护服务器

传统方式需要投入大量时间和精力。后端即服务(BaaS) 的出现,就是为了解决这个问题。

提到 BaaS,大多数人首先想到的是 Firebase。但 Firebase 是 Google’s 闭源服务,存在数据隐私、定价、语言限制等问题。

今天介绍一款开源的 BaaS 平台——Appwrite,它提供完整的后端解决方案,同时支持完全自托管。

什么是 Appwrite?

Appwrite 是一个开源的后端即服务(BaaS)平台,为 Web、移动端和原生应用提供完整的后端服务。

核心特性:

特性 说明
开源免费 BSD-3 许可证,完全开源
自托管 可部署在自己的服务器
用户认证 支持邮箱、OAuth、SMS 等多种登录方式
数据库 关系型数据库,支持实时订阅
文件存储 图片、视频、文档存储,支持缩略图
云函数 支持多种语言的 Serverless 函数
消息服务 邮件、短信、推送通知
团队协作 团队和权限管理

GitHub 地址: https://github.com/appwrite/appwrite

官网: https://appwrite.io

Appwrite vs Firebase vs Supabase

对比项 Appwrite Firebase Supabase
开源 ✅ BSD-3 ❌ 闭源 ✅ Apache 2.0
数据库类型 关系型 NoSQL 关系型 (PostgreSQL)
数据库 MySQL Firestore PostgreSQL
自托管 ✅ 完全支持 ❌ 不支持 ✅ 完全支持
云函数 ✅ 多语言 ✅ Node.js ✅ 多语言
实时订阅
文件存储
邮件服务 ✅ 内置 ❌ 需集成 ❌ 需集成
推送通知
SDK 支持 20+ 10+ 10+

Appwrite 的独特优势:

  • 专为 Docker 设计,微服务架构
  • 支持多种数据库(MySQL、PostgreSQL、MongoDB)
  • 内置邮件和短信服务
  • 更现代的 API 设计
  • 完善的 SDK(Web、iOS、Android、Flutter、React Native 等)

快速上手

方式一:在线使用

Appwrite 提供免费的云服务,注册即可使用:

  1. 访问 https://cloud.appwrite.io
  2. 使用 GitHub 或 Google 账号登录
  3. 创建第一个项目

方式二:Docker 部署(推荐)

使用 Docker Compose 一键部署:

# 创建目录
mkdir appwrite && cd appwrite

# 下载 docker-compose.yml
curl -L "https://github.com/appwrite/appwrite/raw/main/docker-compose.yml" -o docker-compose.yml

# 启动服务
docker-compose up -d

# 访问管理后台
# http://localhost

首次访问时,需要设置管理员邮箱和密码。

方式三:独立容器部署

docker run -it --rm \
    --name appwrite \
    -p 80:80 \
    -p 443:443 \
    -p 3000:3000 \
    -p 3001:3001 \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v $(pwd)/data:/storage/data:rw \
    appwrite/appwrite:1.5

核心功能详解

1. 用户认证

Appwrite 提供完整的用户认证系统:

支持的登录方式:

方式 说明
邮箱/密码 传统的邮箱密码注册登录
OAuth2.0 Google、GitHub、Facebook、Apple 等
手机号/SMS 手机号 + 验证码登录
匿名访问 临时访问,适用于游客用户
Magic URL 邮箱链接登录

SDK 使用示例:

// Web SDK
import { Client, Account } from "appwrite";

// 初始化客户端
const client = new Client();
client
  .setEndpoint("https://cloud.appwrite.io/v1")
  .setProject("[PROJECT_ID]");

const account = new Account(client);

// 邮箱注册
async function register(email, password, name) {
  await account.create("unique()", email, password, name);
  await account.createEmailSession(email, password);
  return await account.get();
}

// OAuth 登录
async function loginWithGoogle() {
  account.createOAuth2Session(
    'google',
    'http://localhost:3000/callback',
    'http://localhost:3000/error'
  );
}

// 获取当前用户
async function getCurrentUser() {
  return await account.get();
}

// 退出登录
async function logout() {
  await account.deleteSession('current');
}
// iOS SDK (Swift)
import Appwrite

let client = Client()
  .setEndpoint("https://cloud.appwrite.io/v1")
  .setProject("[PROJECT_ID]")

let account = Account(client)

// 邮箱注册
func register(email: String, password: String, name: String) async throws {
  try await account.create(userId: "unique()", email: email, password: password, name: name)
  try await account.createEmailSession(email: email, password: password)
}

2. 数据库

Appwrite 支持关系型数据库,提供集合、文档、索引管理:

核心概念:

概念 说明
Database 数据库
Collection 集合(相当于表)
Attribute 属性(字段)
Index 索引
Document 文档(记录)

SDK 使用示例:

import { Client, Databases, ID, Query } from "appwrite";

const databases = new Databases(client);

// 创建文档
async function createPost(title, content, authorId) {
  const post = await databases.createDocument(
    '[DATABASE_ID]',
    '[COLLECTION_ID]',
    ID.unique(),
    {
      title: title,
      content: content,
      authorId: authorId,
      createdAt: new Date().toISOString()
    }
  );
  return post;
}

// 查询文档
async function getPosts(limit = 10) {
  const posts = await databases.listDocuments(
    '[DATABASE_ID]',
    '[COLLECTION_ID]',
    [
      Query.orderDesc('$createdAt'),
      Query.limit(limit)
    ]
  );
  return posts.documents;
}

// 实时订阅
function subscribeToPosts(callback) {
  const unsubscribe = client.subscribe(
    'databases.[DATABASE_ID].collections.[COLLECTION_ID].documents',
    (response) => {
      if (response.events.includes('databases.*.collections.*.documents.*.create')) {
        callback(response.payload);
      }
    }
  );
  return unsubscribe;
}

权限管理:

Appwrite 提供细粒度的文档权限控制:

// 创建时设置权限
{
  "$id": ID.unique(),
  "title": "My Post",
  "$permissions": {
    "read": ["user:123", "team:456"],
    "write": ["user:123"],
    "delete": ["user:123", "role:admin"]
  }
}

3. 文件存储

Appwrite 提供文件上传、存储和管理功能:

import { Client, Storage, Buckets, ID } from "appwrite";

const storage = new Storage(client);

// 上传文件
async function uploadFile(file) {
  const uploaded = await storage.createFile(
    '[BUCKET_ID]',
    ID.unique(),
    file
  );
  return uploaded;
}

// 获取文件预览
function getFilePreview(fileId, width = 300, height = 300) {
  return `${ENDPOINT}/storage/buckets/[BUCKET_ID]/files/${fileId}/preview?width=${width}&height=${height}`;
}

// 下载文件
async function downloadFile(fileId) {
  const result = await storage.getFileDownload('[BUCKET_ID]', fileId);
  return result;
}

// 删除文件
async function deleteFile(fileId) {
  await storage.deleteFile('[BUCKET_ID]', fileId);
}

图片处理:

// 直接在 URL 中指定参数
const imageUrl = `${ENDPOINT}/storage/buckets/[BUCKET_ID]/files/[FILE_ID]/preview?
  width=800&
  height=600&
  gravity=center&
  quality=80&
  borderWidth=2&
  borderColor=000000`;

4. 云函数

Appwrite 支持 Serverless 函数,可以使用多种语言编写:

支持的运行时:

语言 版本
Node.js 16, 18, 20
PHP 8.0, 8.1, 8.2
Ruby 3.0, 3.1
Python 3.9, 3.10, 3.11
Dart 2.18
Go 1.18, 1.20
.NET 6.0, 7.0

函数示例(Node.js):

module.exports = async function (req, res) {
  const db = req.variables['APPWRITE_FUNCTION_DATA'];
  const payload = JSON.parse(req.payload || '{}');

  // 处理请求
  const result = {
    success: true,
    message: 'Hello from Appwrite Function!',
    input: payload,
    timestamp: new Date().toISOString()
  };

  // 返回响应
  res.json(result);
};

函数触发方式:

触发方式 说明
HTTP 通过 HTTP 请求触发
定时 Cron 任务调度
事件 根据数据库/存储事件触发
手动 手动调用

5. 消息服务

Appwrite 内置消息服务,支持邮件和短信:

import { Client, Messaging } from "appwrite";

const messaging = new Messaging(client);

// 发送邮件
async function sendEmail(to, subject, content) {
  const message = await messaging.createEmail(
    ID.unique(),
    to,
    subject,
    content
  );
  return message;
}

// 发送短信
async function sendSMS(to, message) {
  const result = await messaging.createSMS(
    ID.unique(),
    to,
    message
  );
  return result;
}

// 发送推送通知
async function sendPushNotification(userId, title, body) {
  const notification = await messaging.createPush(
    ID.unique(),
    title,
    body,
    [userId]
  );
  return notification;
}

SDK 支持

Appwrite 提供 20+ 官方 SDK:

平台 SDK
Web / React @appwrite/sdk-for-web
React Native @appwrite/sdk-for-react-native
Flutter appwrite
iOS / Swift appwrite
Android / Kotlin appwrite
Node.js @appwrite/sdk-for-node
Python @appwrite/sdk-for-python
PHP @appwrite/sdk-for-php
Ruby @appwrite/sdk-for-ruby
Go @appwrite/sdk-for-go
.NET @appwrite/sdk-for-dotnet
Deno @appwrite/sdk-for-deno

管理后台

Appwrite 提供现代化的管理后台,可以可视化操作:

  • 项目概览:查看 API 调用量、用户活跃度
  • 数据库管理:可视化创建集合、属性、索引
  • 用户管理:查看用户列表、用户详情、会话管理
  • 存储管理:上传文件、管理桶、配置权限
  • 函数管理:创建函数、查看日志、监控执行
  • 消息管理:配置邮件/短信模板、查看发送记录

部署架构

Appwrite 采用微服务架构,每个服务独立运行:

┌─────────────────────────────────────────────────┐
│                    Nginx (反向代理)               │
├─────────────────────────────────────────────────┤
│  Traefik (API 网关)                            │
├────────────┬────────────┬────────────┬─────────┤
│ Appwrite   │ Appwrite   │ Appwrite   │ Appwrite│
│ Console    │ API        │ Auth       │ Storage │
├────────────┴────────────┴────────────┴─────────┤
│           Redis (缓存/队列)                      │
├─────────────────────────────────────────────────┤
│           InfluxDB (时序数据)                   │
├─────────────────────────────────────────────────┤
│           MariaDB / MongoDB (主数据库)          │
└─────────────────────────────────────────────────┘

常见问题

Q:Appwrite 和 Supabase 有什么区别?

A:

  • Appwrite 更注重微服务架构和 Docker 部署
  • Supabase 基于 PostgreSQL,更像传统关系型数据库
  • Appwrite 支持更多类型的数据库(MySQL、PostgreSQL、MongoDB)
  • Appwrite 内置更多服务(邮件、短信、推送通知)

Q:性能如何?能用于生产环境吗?

A:Appwrite 已被众多公司用于生产环境。但需要注意:

  • 合理配置服务器资源
  • 使用合适的数据库
  • 配置缓存和 CDN
  • 做好监控和日志

Q:数据安全如何保证?

A:

  • 所有数据传输使用 HTTPS
  • 文件存储支持加密
  • 细粒度的权限控制
  • 支持自托管,数据完全可控

Q:如何升级 Appwrite?

A:

# 拉取最新版本
docker pull appwrite/appwrite:1.6

# 停止旧容器
docker-compose down

# 启动新版本
docker-compose up -d

适用场景

推荐使用:

  • 快速原型和 MVP 开发
  • 移动应用后端
  • SaaS 产品后端
  • 需要数据隐私控制的项目
  • 追求开源可控的团队

不推荐使用:

  • 超大规模分布式系统
  • 需要复杂 SQL 查询的场景
  • 对延迟要求极高的实时应用

总结

Appwrite 用"开源 + Docker + 微服务"的架构,为后端即服务提供了一个现代化、可扩展的解决方案。

核心优势回顾:

  • 完全开源:BSD-3 许可,代码透明可审计
  • 自托管:数据完全可控,满足合规要求
  • 功能完备:认证、数据库、存储、云函数、消息一应俱全
  • 多 SDK:20+ 官方 SDK,支持所有主流平台
  • 现代化架构:Docker 微服务,易于扩展
  • 开发者友好:完善的文档和社区支持

对于追求开源、数据可控、快速开发的团队,Appwrite 是构建后端的绝佳选择。


本文由无边界科技技术团队分享,专注软件开发与技术解决方案。

官网:wubianj.com

© 版权归无边界科技所有,版权所有。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐