Cài PostgreSQL + Redis Trên VPS 2026: Hướng Dẫn Từ A-Z Cho Người Mới
Nếu bạn đang chạy web app trên VPS, PostgreSQL và Redis là bộ đôi database không thể thiếu. PostgreSQL xử lý dữ liệu quan hệ mạnh mẽ, Redis làm cache và message queue siêu nhanh. Cùng lắp cả hai lên VPS Ubuntu 24.04 trong 15 phút.
📊 Con số thực tế: WordPress + Redis cache giảm 80% query MySQL, thời gian load từ 2.8s xuống 0.4s. PostgreSQL full-text search nhanh hơn MySQL 3-5x với dataset trên 1 triệu row.
1. PostgreSQL vs MySQL: Chọn Gì Cho VPS 2026?
| Tiêu Chí | PostgreSQL | MySQL/MariaDB |
|---|---|---|
| ACID Compliance | Hoàn toàn (SERIALIZABLE mặc định) | Phụ thuộc engine (InnoDB mới đủ) |
| JSON Support | JSONB — index, query JSON siêu nhanh | JSON — hỗ trợ nhưng chậm hơn |
| Full-Text Search | Tích hợp sẵn, hỗ trợ nhiều ngôn ngữ | Cần plugin hoặc Elasticsearch |
| Concurrency | MVCC xuất sắc, không lock khi đọc | MVCC tốt nhưng kém hơn ở write-heavy |
| Extension | PostGIS, TimescaleDB, pgvector (AI) | Hạn chế hơn |
| RAM tối thiểu | ~512MB | ~256MB |
| Phù hợp | App phức tạp, analytics, AI/vector | WordPress, app đơn giản, shared hosting |
🎯 Quy tắc chọn: Làm app mới từ đầu → PostgreSQL. Đang dùng WordPress/Laravel cũ → MySQL. Cần vector search cho AI → PostgreSQL + pgvector. Cần time-series data → PostgreSQL + TimescaleDB.
2. Cài PostgreSQL 16 Trên Ubuntu 24.04
# Import PostgreSQL repo
sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
# Cài PostgreSQL 16
sudo apt update
sudo apt install postgresql-16 postgresql-client-16 -y
# Start & enable
sudo systemctl start postgresql
sudo systemctl enable postgresql
sudo systemctl status postgresql
# Đổi password user postgres
sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'YourStrongPassword2026!';"
# Tạo database và user cho app
sudo -u postgres psql <
2.1. Cho Phép Kết Nối Từ Xa
# Sửa postgresql.conf
sudo nano /etc/postgresql/16/main/postgresql.conf
# Tìm và sửa:
listen_addresses = 'localhost' → listen_addresses = '*'
# Sửa pg_hba.conf — cho phép IP app server kết nối
sudo nano /etc/postgresql/16/main/pg_hba.conf
# Thêm dòng:
host all all 192.168.1.0/24 md5
# Restart
sudo systemctl restart postgresql
# Test kết nối từ xa
psql -h YOUR_VPS_IP -U myapp -d myapp_db
2.2. Tối Ưu PostgreSQL Config
# Backup config gốc
sudo cp /etc/postgresql/16/main/postgresql.conf /etc/postgresql/16/main/postgresql.conf.bak
# Sửa các thông số chính
sudo nano /etc/postgresql/16/main/postgresql.conf
# === CHO VPS 4GB RAM ===
shared_buffers = 1GB # 25% RAM
effective_cache_size = 3GB # 75% RAM
maintenance_work_mem = 256MB
work_mem = 32MB # Tăng nếu query phức tạp
wal_buffers = 16MB
random_page_cost = 1.1 # SSD/NVMe
effective_io_concurrency = 200
max_connections = 100
# === CHO VPS 8GB RAM ===
shared_buffers = 2GB
effective_cache_size = 6GB
maintenance_work_mem = 512MB
work_mem = 64MB
max_connections = 200
sudo systemctl restart postgresql
3. Cài Redis 7 Trên Ubuntu 24.04
# Cài từ repo chính thức
sudo apt update
sudo apt install redis-server -y
# Start & enable
sudo systemctl start redis-server
sudo systemctl enable redis-server
# Kiểm tra
redis-cli ping
# → PONG
3.1. Cấu Hình Redis Cho Production
# Backup config
sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.bak
# Sửa config
sudo nano /etc/redis/redis.conf
# === Những dòng cần sửa ===
bind 127.0.0.1 # Chỉ listen localhost (dùng app trên cùng VPS)
# bind 0.0.0.0 # Nếu app ở VPS khác — nhớ bật requirepass!
requirepass YourStrongRedisPassword2026!
maxmemory 512mb # Giới hạn RAM Redis dùng (VPS 4GB)
maxmemory-policy allkeys-lru # Tự xóa key ít dùng khi đầy
save 900 1 # RDB snapshot: save nếu ít nhất 1 key thay đổi trong 900s
save 300 10
save 60 10000
appendonly yes # AOF persistence — an toàn hơn
appendfsync everysec # Sync mỗi giây
# Restart
sudo systemctl restart redis-server
# Test auth
redis-cli -a YourStrongRedisPassword2026! ping
3.2. Dùng Redis Trong Ứng Dụng
Node.js (ioredis):
const Redis = require('ioredis');
const redis = new Redis({
host: '127.0.0.1',
port: 6379,
password: 'YourStrongRedisPassword2026!'
});
// Cache user data — TTL 1 giờ
async function getUser(userId) {
const cached = await redis.get(`user:${userId}`);
if (cached) return JSON.parse(cached);
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
return user;
}
// Rate limiting — 100 request/phút
async function rateLimit(ip) {
const key = `ratelimit:${ip}`;
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, 60);
return count <= 100;
}
PHP (Predis):
require 'vendor/autoload.php';
$redis = new Predis\Client([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'YourStrongRedisPassword2026!'
]);
// Cache
$redis->setex('page:home', 300, $html);
// Session store
ini_set('session.save_handler', 'redis');
ini_set('session.save_path', 'tcp://127.0.0.1:6379?auth=YourStrongRedisPassword2026!');
4. Backup PostgreSQL + Redis Tự Động
4.1. Backup PostgreSQL Hàng Ngày
# Tạo script backup
sudo nano /usr/local/bin/pg-backup.sh
#!/bin/bash
BACKUP_DIR="/var/backups/postgresql"
DATE=$(date +%Y%m%d_%H%M)
DB_LIST="myapp_db"
mkdir -p $BACKUP_DIR
for DB in $DB_LIST; do
sudo -u postgres pg_dump -Fc $DB > "$BACKUP_DIR/${DB}_${DATE}.dump"
done
# Giữ backup 7 ngày
find $BACKUP_DIR -name "*.dump" -mtime +7 -delete
# Sync lên cloud (tuỳ chọn)
# rclone sync $BACKUP_DIR remote:postgresql-backup/
sudo chmod +x /usr/local/bin/pg-backup.sh
# Crontab: backup lúc 2h sáng mỗi ngày
echo "0 2 * * * /usr/local/bin/pg-backup.sh >> /var/log/pg-backup.log 2>&1" | sudo crontab -
4.2. Backup Redis
# Redis tự backup qua RDB + AOF (đã cấu hình ở trên)
# File: /var/lib/redis/dump.rdb (RDB)
# File: /var/lib/redis/appendonly.aof (AOF)
# Backup thủ công
sudo cp /var/lib/redis/dump.rdb /var/backups/redis/dump_$(date +%Y%m%d).rdb
# Hoặc trigger SAVE từ redis-cli
redis-cli -a YourStrongRedisPassword2026! BGSAVE
5. Giám Sát PostgreSQL + Redis
# PostgreSQL — active connections
sudo -u postgres psql -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'active';"
# PostgreSQL — slow queries (>1s)
sudo -u postgres psql -c "SELECT query, mean_exec_time FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 5;"
# Redis — memory usage
redis-cli -a YourStrongRedisPassword2026! INFO memory | grep used_memory_human
# Redis — hit rate
redis-cli -a YourStrongRedisPassword2026! INFO stats | grep keyspace
6. So Sánh Chi Phí: PostgreSQL + Redis Trên Các Nền Tảng
| Giải Pháp | Cấu Hình | Giá/Tháng | Phù Hợp |
|---|---|---|---|
| Tự cài trên TrumVPS | 4 CPU, 4GB RAM, NVMe | ~200K | App vừa & nhỏ |
| Tự cài trên VPS mạnh | 8 CPU, 16GB RAM, NVMe | ~800K-1.2M | App lớn, nhiều user |
| AWS RDS + ElastiCache | db.t4g.medium + cache.t4g.micro | ~$80 (2M) | Enterprise, cần managed |
| DigitalOcean Managed DB | 2GB RAM PostgreSQL + 1GB Redis | ~$30 (750K) | Mid-tier, thích managed |
| Supabase (PostgreSQL) | Free tier 500MB | 0đ → $25/tháng | Dự án cá nhân, prototype |
💰 Tiết kiệm nhất: Tự cài PostgreSQL + Redis trên cùng 1 VPS 4GB RAM — chỉ ~200K/tháng, đủ cho app 10K-50K user/ngày. Lên 8GB RAM khi vượt 100K user.
🚀 Sẵn Sàng Cài Database Cho App Của Bạn?
Thuê VPS 4GB RAM từ 200K/tháng, cài PostgreSQL + Redis trong 15 phút theo hướng dẫn trên.
Thuê VPS Ngay →Xem thêm:
- Cài Docker & Docker Compose Trên VPS — chạy PostgreSQL + Redis trong container
- Cài Đặt & Quản Lý Database Trên VPS — tổng quan các DB engine
- Tối Ưu MySQL/MariaDB Trên VPS — nếu bạn dùng MySQL
- Monitor VPS Với Grafana + Prometheus — dashboard PostgreSQL + Redis metrics
- Backup Tự Động Website Trên VPS — backup cả code + DB