0%

安裝mongoDB

#安裝mongoDB

system :
ubuntu 16.04
mongoDB 3.4

##匯入 MongoDB 公開的 GPG 金鑰:

1
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

##建立 /etc/apt/sources.list.d/mongodb-org-3.4.list:

1
echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

##安裝 MongoDB:

1
sudo apt-get install -y mongodb-org

如果出現
mongodb WARNING: The following packages cannot be authenticated!
這是因為安裝包沒有被簽名
但可以加上 –force-yes 強制安裝

1
sudo apt-get install -y mongodb-org --force-yes

##建立MongoDB服務
如果要使用以下服務的指令對mongodb進行操作,都會跳出
Failed to start mongod.service: Unit mongod.service not found.的錯誤,這個原因是我們還沒有將mongodDB註冊為service

1
2
3
sudo service mongodb start
sudo service mongodb stop
sudo service mongodb restart

要將mongodb註冊為service,首先要先建立並且編輯mongodb.service文件

1
sudo vim /etc/systemd/system/mongodb.service

接著將以下內容貼入,完成後按ESC,並且輸入:wq,儲存並且離開

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#Unit contains the dependencies to be satisfied before the service is started.
[Unit]
Description=MongoDB Database
After=network.target
Documentation=https://docs.mongodb.org/manual
# Service tells systemd, how the service should be started.
# Key `User` specifies that the server will run under the mongodb user and
# `ExecStart` defines the startup command for MongoDB server.
[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf
# Install tells systemd when the service should be automatically started.
# `multi-user.target` means the server will be automatically started during boot.
[Install]
WantedBy=multi-user.target

接著更新服務

1
systemctl daemon-reload

開啟mongodb服務

1
sudo systemctl start mongodb

可以透過以下指令查看mongodb的狀況

1
sudo systemctl status mongodb

如果出現了

1
Process: 5001 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited

直接重開機就可以解決了

1
sudo reboot

可以透過觀看port的狀態來看mongod服務有沒有啟用,mongod的port是27017

1
netstat -plntu

也可以透過lsof的指令來看port 27017有沒有被使用

1
lsof -i :27017

如果沒辦法使用lsof,那應該是沒有安裝,可以透過下列指令安裝lsof,安裝完畢之後再輸入上面指令就可以使用了

1
2
sudo apt update
sudo apt install lsof

讓mongodb在開機時啟動

1
sudo systemctl enable mongodb

但這一步我做起來怪怪的,一直出現Failed to execute operation: Invalid argument,後來我直接把service的檔案放到/etc/systemd/system/multi-user.target.wants再重新開機就可以啟用了

##移除 MongoDB
移除所有mongodb相關套件

1
2
3
4
sudo apt-get clean  //刪除暫存的所有安裝包
sudo apt-get autoclean //刪除已經安裝過的安裝包
sudo apt-get purge mongodb
sudo apt autoremove //刪除mongodb依賴的相關包

刪除所有的記錄檔與資料庫:

1
2
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

在 Ubuntu Linux 中安裝 MongoDB 資料庫
mongodb解除安裝再重灌
apt-get指令的autoclean,clean,autoremove的區別
MongoDB安裝異常
Apt-get fails on 16.04 installing mongodb
Mongodb not working on Ubuntu 16.04
Install MongoDB on Ubuntu 16.04 LTS
Ubuntu下node+mongodb環境搭建完全實踐
Attempting to enable systemd script results “Failed to execute…”