Cài Appwrite Trên VPS TrumVPS - Tự Host Firebase Alternative, Backend Cho Mobile/Web App Chỉ Từ 80K/Tháng
Bạn đang build 1 mobile app hoặc web app? Bạn biết mình cần authentication (đăng nhập/đăng ký), database, file storage, push notification, serverless functions — nhưng không muốn mất 2 tuần để code từng cái một?
Firebase của Google là lựa chọn phổ biến nhất — nhưng chi phí có thể vượt tầm kiểm soát khi app scale. Spark plan miễn phí giới hạn 50K reads/ngày. Blaze plan tính tiền theo usage: 1 triệu users active có thể tốn $100-500/tháng. Và quan trọng nhất: vendor lock-in — một khi đã dùng Firebase, rất khó migrate đi nơi khác.
Appwrite là Firebase alternative mã nguồn mõ, cho phép bạn tự host toàn bộ backend trên VPS TrumVPS chỉ từ 80K/tháng. Auth, Database, Storage, Functions, Realtime, Messaging — tất cả trong 1 nền tảng, không giới hạn request, không phí ẩn.
Appwrite Là Gì? Tại Sao Developer Yêu Thích?
Appwrite là nền tảng Backend-as-a-Service (BaaS) mã nguồn mở, cung cấp mọi thứ bạn cần để build ứng dụng hiện đại:
- 🔐 Authentication: Email/Password, OAuth2 (Google, GitHub, Apple, Facebook, Microsoft...), Phone (SMS), Anonymous, JWT, 2FA, Magic Link. Hỗ trợ 30+ providers
- 🗄️ Database: NoSQL document database với query mạnh mẽ, index, relationships, realtime subscriptions
- 📦 Storage: Upload file, ảnh, video với permission chi tiết. Tự động nén ảnh, preview, antivirus scan
- ⚡ Functions: Serverless functions chạy code backend với Node.js, Python, PHP, Ruby, Deno, Dart, .NET, Java, Kotlin, Swift
- 🔔 Messaging: Push notifications (FCM, APNs), email (SMTP/Mailgun/Sendgrid), SMS (Twilio/Vonage)
- 🔄 Realtime: WebSocket subscriptions cho database, storage events — cập nhật UI realtime
- 🌍 Locale: Hỗ trợ đa ngôn ngữ cho end-users
- 🛡️ Security: Rate limiting, IP whitelist/blacklist, abuse detection, max session limits
So Sánh Appwrite vs Firebase vs Supabase
| Tiêu chí | Appwrite (VPS 160K) | Firebase (Blaze) | Supabase Cloud (Pro) | Supabase Self-host |
|---|---|---|---|---|
| Giá / tháng | 160K VNĐ (cố định) | $0.18/100K reads ~$50-500+ | $25 (~625K) | ~160K (VPS) |
| Authentication | ✅ 30+ providers | ✅ Tốt | ✅ Tốt | ✅ |
| Database | NoSQL (MariaDB) | Firestore (NoSQL) | PostgreSQL (SQL) | PostgreSQL |
| Storage | ✅ + antivirus | ✅ | ✅ | ✅ |
| Functions | ✅ 10+ runtimes | ✅ Node.js, Python | ✅ Deno/TS | ✅ |
| Realtime | ✅ WebSocket | ✅ WebSocket | ✅ WebSocket | ✅ |
| Push Notification | ✅ FCM + APNs | ✅ FCM | ❌ (dùng bên thứ 3) | ❌ |
| GraphQL API | ✅ Có sẵn | ❌ (REST + SDK) | ✅ PostgREST | ✅ |
| REST API | ✅ | ⚠ Qua Cloud Func | ✅ | ✅ |
| Dashboard UI | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Mã nguồn mở | ✅ BSD-3 | ❌ Proprietary | ✅ Apache 2.0 | ✅ |
| Vendor lock-in | ❌ Không | ⚡ Rất cao | ⚠ Trung bình | ❌ Không |
| Mobile SDK | ✅ Flutter, RN, iOS, Android | ✅ Đầy đủ | ✅ Flutter, JS | ✅ |
| Web SDK | ✅ JS, Vue, React, Angular, Svelte | ✅ JS | ✅ JS | ✅ |
Yêu Cầu Hệ Thống
- VPS TrumVPS gói 80K (2GB RAM, 2 CPU) — tối thiểu
- VPS TrumVPS 160K+ (4GB RAM, 4 CPU) — khuyến nghị cho production
- Ubuntu 22.04 hoặc 24.04
- Ổ cứng: Tối thiểu 30GB cho dev, 50GB+ cho production
- Domain: 1 domain/subdomain cho Appwrite (vd: appwrite.yourdomain.com)
- Docker & Docker Compose (đã cài sẵn)
Bước 1: Cài Docker & Docker Compose
Nếu VPS chưa có Docker:
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER
newgrp docker
Bước 2: Cài Đặt Appwrite
Appwrite cung cấp script cài đặt tự động, cực kỳ đơn giản:
# Tải và chạy script cài đặt
docker run -it --rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:1.6.0
Script sẽ hỏi bạn các thông tin:
? Choose your Appwrite plan (oss/self-hosted): oss
? Enter your Appwrite hostname: appwrite.yourdomain.com
? HTTP port (default 80): 80
? HTTPS port (default 443): 443
? Enter your email: your@email.com
? Enter your Appwrite secret key (auto-generated): [Enter để auto]
? Create _APP_ console internal key (auto-generated): [Enter để auto]
appwrite.yourdomain.com phải trỏ DNS về IP VPS trước khi cài. Appwrite sẽ tự động request SSL Let's Encrypt trong quá trình install.
Sau khi cài xong, Appwrite sẽ hiển thị credentials:
✅ Appwrite installed successfully!
Your Appwrite console is ready at:
https://appwrite.yourdomain.com
Create your root user at:
https://appwrite.yourdomain.com/register
Installation complete! Start building amazing apps! 🚀
Bước 3: Tạo Root User & Project Đầu Tiên
- Truy cập
https://appwrite.yourdomain.com/register - Đăng ký tài khoản root (admin) với email + password
- Đăng nhập → vào Create Project
- Đặt tên project (vd: MyAwesomeApp)
- Chọn platform: Web, Flutter, iOS, Android...
- Copy Project ID và API Endpoint
Bước 4: Cấu Hình Authentication
Trong Appwrite Console → Project → Auth → Settings:
Email/Password Auth
# Bật Email/Password
Auth → Settings → Email/Password: ENABLED
# Giới hạn session
Max Sessions: 5 (giới hạn số thiết bị đăng nhập/user)
OAuth2 Google Login
- Vào Google Cloud Console → Create OAuth Client ID
- Authorized redirect URI:
https://appwrite.yourdomain.com/v1/account/sessions/oauth2/callback/google - Copy Client ID và Client Secret
- Trong Appwrite Auth Settings → Google → Enabled → điền credentials
GitHub OAuth
- GitHub → Settings → Developer Settings → OAuth Apps → New OAuth App
- Authorization callback URL:
https://appwrite.yourdomain.com/v1/account/sessions/oauth2/callback/github - Copy Client ID & Secret → paste vào Appwrite
Bước 5: Tạo Database & Collections
Trong Appwrite Console → Databases → Create Database:
Database name: myapp_db
# Tạo collection "posts"
Collection name: posts
Permissions: Document level security
# Thêm attributes (schema-less nhưng có validation)
- title: string (required, max 255)
- content: string (required, max 50000)
- author_id: string (required)
- published: boolean (default: false)
- created_at: datetime
# Tạo indexes để query nhanh
- Index: author_id (key) — order ASC
- Index: published (key) — order DESC
- Index: created_at (key) — order DESC
Bước 6: Tích Hợp Appwrite Với Ứng Dụng
Web (JavaScript)
npm install appwrite
import { Client, Account, Databases, ID, Query } from 'appwrite';
// Initialize
const client = new Client()
.setEndpoint('https://appwrite.yourdomain.com/v1')
.setProject('YOUR_PROJECT_ID');
const account = new Account(client);
const databases = new Databases(client);
// Register user
const user = await account.create(
ID.unique(),
'user@email.com',
'strong_password',
'Username'
);
// Login
const session = await account.createEmailPasswordSession(
'user@email.com',
'strong_password'
);
// Create document
const post = await databases.createDocument(
'myapp_db', // Database ID
'posts', // Collection ID
ID.unique(),
{
title: 'Hello Appwrite!',
content: 'First post content...',
author_id: user.$id,
published: true,
created_at: new Date().toISOString()
}
);
// Query documents with filter
const posts = await databases.listDocuments(
'myapp_db', 'posts',
[
Query.equal('published', true),
Query.orderDesc('created_at'),
Query.limit(20)
]
);
// Realtime subscription - listen for new posts
const unsubscribe = client.subscribe(
'databases.myapp_db.collections.posts.documents',
(response) => {
console.log('Realtime update:', response.payload);
}
);
Flutter (Mobile App)
dependencies:
appwrite: ^13.0.0
import 'package:appwrite/appwrite.dart';
final client = Client()
.setEndpoint('https://appwrite.yourdomain.com/v1')
.setProject('YOUR_PROJECT_ID')
.setSelfSigned(status: false);
final account = Account(client);
final databases = Databases(client);
final storage = Storage(client);
// Create account
final user = await account.create(
userId: ID.unique(),
email: 'user@email.com',
password: 'strong_password',
name: 'Username',
);
// Upload file
final file = await storage.createFile(
bucketId: 'avatars',
fileId: ID.unique(),
file: InputFile.fromPath(path: '/path/to/avatar.jpg'),
);
// Get file preview URL
final previewUrl = storage.getFilePreview(
bucketId: 'avatars',
fileId: file.$id,
width: 200,
height: 200,
).toString();
React/Next.js
// hooks/useAppwrite.ts
import { Client, Account, Databases } from 'appwrite';
const client = new Client()
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!)
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT!);
export const account = new Account(client);
export const databases = new Databases(client);
export { client, ID, Query } from 'appwrite';
// components/Login.tsx
import { account, ID } from '@/hooks/useAppwrite';
async function login(email: string, password: string) {
try {
await account.createEmailPasswordSession(email, password);
const user = await account.get();
return user;
} catch (error) {
console.error('Login failed:', error);
}
}
Bước 7: Serverless Functions
Appwrite Functions cho phép chạy code backend mà không cần server riêng. Ví dụ: gửi email chào mừng khi user đăng ký.
# Cài Appwrite CLI
npm install -g appwrite-cli
appwrite login
appwrite init function
# Tạo function mới
appwrite create function \
--functionId welcome-email \
--name "Welcome Email" \
--runtime node-18.0 \
--execute ["users"]
src/main.js (hàm gửi welcome email):
const sdk = require('node-appwrite');
module.exports = async function(context) {
const { req, res, log, error } = context;
// Appwrite SDK
const client = new sdk.Client()
.setEndpoint(context.req.headers['x-appwrite-url-endpoint'])
.setProject(context.req.headers['x-appwrite-project'])
.setKey(context.req.headers['x-appwrite-key']);
const users = new sdk.Users(client);
const mail = new sdk.Messaging(client);
const userId = JSON.parse(req.body).userId;
const user = await users.get(userId);
// Gửi email chào mừng
await mail.createEmail(
sdk.ID.unique(),
'Welcome to MyApp! 🎉',
`Chào ${user.name}!
Cảm ơn bạn đã đăng ký...
`,
[], [], [], [], [],
user.email
);
return res.json({ success: true });
};
Appwrite Architecture - DevOps View
Khi cài Appwrite, Docker Compose chạy các containers sau trên VPS của bạn:
| Container | Vai Trò | Port |
|---|---|---|
| appwrite | API server chính (PHP Swoole) | 80, 443 |
| appwrite-realtime | WebSocket server cho realtime subscriptions | internal |
| appwrite-worker-database | Xử lý database jobs | internal |
| appwrite-worker-functions | Chạy serverless functions | internal |
| appwrite-worker-builds | Build function deployments | internal |
| appwrite-worker-mails | Gửi email qua SMTP | internal |
| mariadb | Database chính (MariaDB 10.11) | 3306 |
| redis | Cache + Queue | 6379 |
| influxdb | Metrics & Usage stats | 8086 |
| telegraf | Collect system metrics | internal |
| appwrite-executor | Sandbox cho function execution | internal |
Monitoring Appwrite
# Kiểm tra status tất cả containers
docker compose -f ~/appwrite/docker-compose.yml ps
# Xem logs realtime
docker compose -f ~/appwrite/docker-compose.yml logs -f
# Kiểm tra usage (CPU, RAM per container)
docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"
# Backup database
docker exec -t appwrite-mariadb mysqldump -u root -p"ROOT_PASSWORD" appwrite > backup.sql
# Restart service nếu có vấn đề
docker compose -f ~/appwrite/docker-compose.yml restart
Cập Nhật Appwrite
Appwrite cập nhật thường xuyên (mỗi 2-4 tuần có bản mới). Cách update:
cd ~/appwrite
# Pull image mới
docker compose pull
# Restart với image mới
docker compose up -d --remove-orphans
# Chạy migration (nếu có thay đổi schema)
docker compose exec appwrite migrate
So Sánh Chi Phí Thực Tế: Appwrite vs Firebase
| Kịch Bản | Appwrite (VPS TrumVPS) | Firebase Blaze | Tiết Kiệm |
|---|---|---|---|
| 1K users, 50K reads/ngày | 80K (VPS 2GB) | ~$18/tháng (450K) | 82% |
| 5K users, 200K reads/ngày | 160K (VPS 4GB) | ~$55/tháng (1.4M) | 88% |
| 20K users, 1M reads/ngày | 320K (VPS 8GB) | ~$220/tháng (5.5M) | 94% |
| 100K users, 5M reads/ngày | 560K (VPS 16GB) + CDN | ~$800/tháng (20M) | 97% |
Câu Hỏi Thường Gặp
Appwrite có phù hợp cho production không?
Có. Appwrite đã đạt 44K+ GitHub stars, được dùng trong production bởi nhiều startup và enterprise. Version 1.6 (2025) đã rất ổn định. Tuy nhiên cần lưu ý: tự host đồng nghĩa với việc bạn tự quản lý backup, monitoring, security patches. Không có managed service lo hộ bạn.
Tôi nên chọn Appwrite hay Supabase?
Tùy nhu cầu:
- Chọn Appwrite nếu bạn cần: mobile-focused (Flutter, React Native), push notifications có sẵn, nhiều OAuth providers, NoSQL database, serverless functions viết bằng nhiều ngôn ngữ
- Chọn Supabase nếu bạn cần: SQL database (PostgreSQL), Row-Level Security mạnh, realtime subscriptions tốt hơn, edge functions (Deno), hệ sinh thái Postgres extensions
Appwrite có hỗ trợ realtime cho Flutter app không?
Có — rất tốt. Appwrite có Flutter SDK first-class (chính đội ngũ Appwrite phát triển). Realtime subscriptions hoạt động qua WebSocket, hỗ trợ lắng nghe thay đổi trên Documents và Files. Flutter + Appwrite là combo rất phổ biến trong cộng đồng.
Có migrate được từ Firebase sang Appwrite không?
Có, nhưng cần effort. Bạn cần:
- Export Auth users từ Firebase Auth (có script hỗ trợ)
- Export Firestore data → transform → import vào Appwrite Database
- Viết lại code SDK (API khác nhau, không drop-in replacement)
- Thời gian migrate ước tính: 1-4 tuần tùy độ phức tạp của app