一、安裝數據庫服務器(以MySQL和PostgreSQL為例)
sudo apt update,確保系統獲取最新軟件包信息。sudo apt install mysql-server -y,自動安裝MySQL主程序及依賴。sudo mysql_secure_installation,按提示設置root密碼、刪除匿名用戶、禁止root遠程登錄、刪除測試數據庫。sudo systemctl start mysql啟動服務,sudo systemctl enable mysql設置開機自動啟動。sudo apt update,同步軟件包索引。sudo apt install postgresql postgresql-contrib -y,安裝PostgreSQL服務器及常用擴展(如pg_stat_statements)。sudo systemctl start postgresql啟動服務,sudo systemctl enable postgresql設置開機自啟。sudo -u postgres psql),輸入\q退出,確認命令行工具可用。二、基礎配置(安全與權限管理)
sudo mysql -u root -p),執行ALTER USER 'root'@'localhost' IDENTIFIED BY 'StrongPassword123!'(替換為復雜密碼)。sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf,找到bind-address = 127.0.0.1(默認僅本地訪問),若需遠程訪問可改為0.0.0.0(需謹慎),保存后重啟服務sudo systemctl restart mysql。CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'AppPassword456';創建用戶,GRANT ALL PRIVILEGES ON my_database.* TO 'app_user'@'localhost';授權指定數據庫權限,FLUSH PRIVILEGES;刷新權限表。sudo -u postgres psql),執行ALTER USER postgres WITH PASSWORD 'SecurePostgresPass';設置強密碼。CREATE DATABASE mydb;創建數據庫,CREATE USER myuser WITH ENCRYPTED PASSWORD 'UserPass123';創建用戶,GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;授權,\q退出。sudo nano /etc/postgresql/<version>/main/postgresql.conf(如postgresql.conf),修改max_connections = 100(根據服務器資源調整最大連接數);編輯sudo nano /etc/postgresql/<version>/main/pg_hba.conf,添加host all all 0.0.0.0/0 md5(允許所有IP遠程連接,需配合防火墻設置),保存后重啟服務sudo systemctl restart postgresql。三、服務管理
sudo systemctl start mysql(啟動)、sudo systemctl stop mysql(停止)、sudo systemctl restart mysql(重啟)。sudo systemctl start postgresql(啟動)、sudo systemctl stop postgresql(停止)、sudo systemctl restart postgresql(重啟)。sudo systemctl status mysql(MySQL狀態)、sudo systemctl status postgresql(PostgreSQL狀態),確認服務運行正常(顯示“active (running)”)。四、常用操作命令
mysql -u root -p(登錄root賬戶)、mysql -u app_user -p(登錄普通用戶)。psql -U postgres(登錄postgres用戶)、psql -U myuser -d mydb -h localhost(登錄指定數據庫)。mysqldump -u root -p --all-databases > full_backup.sql(全量備份)、mysql -u root -p < backup.sql(恢復)。pg_dump -U postgres --all-databases > full_backup.sql(全量備份)、psql -U postgres < backup.sql(恢復)。注意事項
sudo apt update && sudo apt upgrade),修復安全漏洞。ufw)放行數據庫端口(MySQL:3306、PostgreSQL:5432),僅允許可信IP訪問。