Quay lại blog
Tháng Năm 23, 2026Hướng dẫn

Cách Cài MongoDB trên Linux VPS

Cài MongoDB Community Edition trên Ubuntu và CentOS, bật xác thực và chạy lệnh cơ bản.

Cách Cài MongoDB trên Linux VPS

MongoDB là cơ sở dữ liệu NoSQL phổ biến cho app hiện đại, API và phân tích. Hướng dẫn này cài MongoDB trên VPS Hiddence và bao gồm thiết lập bảo mật cơ bản.

Cài trên Ubuntu 22.04+

bash
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
mongosh --eval "db.runCommand({ ping: 1 })"

Cài trên RHEL / CentOS / Alma / Rocky

bash
cat <<EOF | sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/\$releasever/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
EOF
sudo yum install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod

Bật xác thực

Tạo user admin trước khi expose MongoDB ra mạng:

bash
mongosh

use admin
db.createUser({
  user: "admin",
  pwd: "StrongPasswordHere",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})

# Edit /etc/mongod.conf — set:
# security:
#   authorization: enabled

sudo systemctl restart mongod

Lệnh cơ bản

bash
mongosh -u admin -p --authenticationDatabase admin

show dbs
use myapp
db.users.insertOne({ name: "test", email: "a@b.com" })
db.users.find()

Thực hành tốt nhất

  • Bind MongoDB tới 127.0.0.1 trừ khi cần truy cập từ xa
  • Dùng firewall chặn cổng 27017 khỏi internet
  • Bật sao lưu định kỳ với mongodump
  • Theo dõi dung lượng đĩa — database tăng nhanh
  • Dùng replica set cho high availability production