Cài Appwrite Trên VPS TrumVPS - Tự Host Firebase Alternative, Backend Cho Mobile/Web App Chỉ Từ 80K/Tháng

📅 29/05/2026 · ⏱ 14 phút đọc · 🏷 Dev · Mobile

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.

💡 Bài toán thực tế: Solo dev build app quản lý công việc với 5K users. Firebase Blaze plan: ~$45/tháng (auth + Firestore reads + storage). Appwrite trên VPS TrumVPS 160K: chỉ 160K/tháng cố định — tiết kiệm ~86%. Và bạn hoàn toàn kiểm soát dữ liệu người dùng của mình.

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:

So Sánh Appwrite vs Firebase vs Supabase

Tiêu chíAppwrite (VPS 160K)Firebase (Blaze)Supabase Cloud (Pro)Supabase Self-host
Giá / tháng160K VNĐ (cố định)$0.18/100K reads ~$50-500+$25 (~625K)~160K (VPS)
Authentication✅ 30+ providers✅ Tốt✅ Tốt
DatabaseNoSQL (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

🔧 Mẹo chọn VPS cho Appwrite: Appwrite chạy ~12 Docker containers (MariaDB, Redis, InfluxDB, Swoole, Executor...). Cần tối thiểu 2GB RAM để chạy ổn định. Với 4GB RAM bạn có thể chạy mượt cho ~1000 concurrent users. Nếu app có nhiều file upload, chọn gói có NVMe SSD.

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]
⚠️ Lưu ý domain: Domain 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

  1. Truy cập https://appwrite.yourdomain.com/register
  2. Đăng ký tài khoản root (admin) với email + password
  3. Đăng nhập → vào Create Project
  4. Đặt tên project (vd: MyAwesomeApp)
  5. Chọn platform: Web, Flutter, iOS, Android...
  6. Copy Project IDAPI Endpoint

Bước 4: Cấu Hình Authentication

Trong Appwrite Console → Project → AuthSettings:

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

  1. Vào Google Cloud Console → Create OAuth Client ID
  2. Authorized redirect URI: https://appwrite.yourdomain.com/v1/account/sessions/oauth2/callback/google
  3. Copy Client IDClient Secret
  4. Trong Appwrite Auth Settings → Google → Enabled → điền credentials

GitHub OAuth

  1. GitHub → Settings → Developer Settings → OAuth Apps → New OAuth App
  2. Authorization callback URL: https://appwrite.yourdomain.com/v1/account/sessions/oauth2/callback/github
  3. Copy Client ID & Secret → paste vào Appwrite

Bước 5: Tạo Database & Collections

Trong Appwrite Console → DatabasesCreate 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
💡 Appwrite Database khác Firestore thế nào? Appwrite dùng MariaDB bên dưới, cho phép query mạnh mẽ hơn Firestore (có compound queries, OR conditions, full-text search). Firestore mạnh về realtime scale nhưng query yếu — nhiều dev phải chuyển sang dùng Elasticsearch/Algolia cho complex queries. Appwrite có query builder mạnh ngay từ đầu.

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:

ContainerVai TròPort
appwriteAPI server chính (PHP Swoole)80, 443
appwrite-realtimeWebSocket server cho realtime subscriptionsinternal
appwrite-worker-databaseXử lý database jobsinternal
appwrite-worker-functionsChạy serverless functionsinternal
appwrite-worker-buildsBuild function deploymentsinternal
appwrite-worker-mailsGửi email qua SMTPinternal
mariadbDatabase chính (MariaDB 10.11)3306
redisCache + Queue6379
influxdbMetrics & Usage stats8086
telegrafCollect system metricsinternal
appwrite-executorSandbox cho function executioninternal
🖥️ Resource usage thực tế: Trên VPS TrumVPS 4GB RAM, 12 containers Appwrite chiếm ~2.5GB RAM khi idle, ~3.5GB khi có 50 users active. CPU idle ~5%, peak ~40%. Hoàn toàn chạy ổn định — không cần VPS quá mạnh.

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ảnAppwrite (VPS TrumVPS)Firebase BlazeTiết Kiệm
1K users, 50K reads/ngày80K (VPS 2GB)~$18/tháng (450K)82%
5K users, 200K reads/ngày160K (VPS 4GB)~$55/tháng (1.4M)88%
20K users, 1M reads/ngày320K (VPS 8GB)~$220/tháng (5.5M)94%
100K users, 5M reads/ngày560K (VPS 16GB) + CDN~$800/tháng (20M)97%
📊 Điểm mấu chốt: Firebase tính tiền theo usage (reads, writes, storage GB, bandwidth). Appwrite tính tiền theo VPS cố định. App càng lớn, Appwrite càng tiết kiệm. Với 100K users, Firebase có thể tốn hàng chục triệu/tháng — trong khi Appwrite vẫn chỉ vài trăm nghìn.

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:

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:

🚀 Sẵn Sàng Tự Host Backend Cho App Của Bạn?

VPS TrumVPS — giá rẻ, NVMe SSD, đủ sức chạy Appwrite + database + storage. Bắt đầu chỉ từ 80K/tháng!

Mã giảm giá: 42089QPI03TI (-9%) — Test miễn phí trước khi thanh toán

⚡ THUÊ VPS CHO APPWRITE NGAY