Ray Lee | 李宗叡
Learn or Die
Published in
4 min readDec 29, 2020

--

Photo by Elaine Casap on Unsplash

# 前言

本篇主要紀錄如何架設一個 NFS server, 並從其他 node 共享檔案

# 環境

VERSION=”19.10 (Eoan Ermine)”

ID=ubuntu

ID_LIKE=debian

PRETTY_NAME=”Ubuntu 19.10"

VERSION_ID=”19.10"

# 安裝

假如你的 apt 無法更新, 執行

sed -i -e 's/archive.ubuntu.com\|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list

# Host

sudo apt update && sudo apt install nfs-kernel-server

# Client

sudo apt update && sudo apt install nfs-common

# 建立分享資料夾

sudo mkdir -p /yourPreferred/directoryLocation

NFS server 預設會將 root 登入者轉為 nobody:nogroup, 因此修改資料夾權限

sudo chown nobody:nogroup /yourPreferred/directoryLocation

# exports 設定檔

  • 設定 exports 檔案, 定義要 export 的資料夾以及細項設定
sudo vim /etc/exports
  • 設定檔
/yourPrederred/directoryLocation *(rw,sync,no_root_squash)
  • 一些設定參數定義
  • 完成設定後, 重啟 server
sudo systemctl restart nfs-kernel-server

# 防火牆設定

# 查看防火牆狀態

sudo ufw status

一般來說, 防火牆越嚴謹越好, 但我們需要開啟特定的 port 讓外部可以存取 NFS server

# 開啟防火牆

  • 請將 client_ip 替換成實際的 client ip
sudo ufw allow from client_ip to any port nfs
  • 查看結果
sudo ufw status

# 掛載到 client 端

# 確認 nfs-common 有啟動

  • 如果 nfs-common 服務沒啟動的話, 啟動它
sudo systemctl start nfs-common
  • 如果顯示 masked, 使用 unmask 又無效的話, 先刪除 service
sudo rm /lib/systemd/system/nfs-config.service
  • 刪除後在 reload daemon
sudo systemctl daemon-reload

然後再 start nfs-common 一次

# 建立空資料夾

  • 建立一個空的資料夾
sudo mkdir -p /yourPrefered/emptyDirectoryLocation

# 掛載

sudo mount -t nfs4 yourHostIp:/ /yourPrefered/emptyDirectoryLocation

這邊要注意一下, 如果使用的是 nfs4, 那 fsid = 0 實際上就代表 root, 即根目錄實際上就是 host exports 出來的資料夾, 所以要使用 yourHostIp:/, 而實際上是掛載到上面在 Host 端建立的資料夾

# 卸載

umount /yourClientMountedDirectory

需注意, 如果你當前位置正在掛載的資料夾, 那會顯示 target is busy, 所以要先離開啦!

# 結語

至此簡易的 NFS 就完成掛載囉, 更多的設定可以參考文末的參考來源。

# 參考資源

--

--

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.