NFS (Network File System) 讓遠端主機的目錄透過網路掛載到本地,操作體驗如同本地檔案系統。嵌入式 Linux 開發中,NFS 是「編譯在伺服器、執行在目標板」的核心基礎設施,支援線上除錯、即時修改,大幅提升開發效率。
# CentOS/RHEL
yum install nfs-utils rpcbind
# Debian/Ubuntu
apt-get install nfs-kernel-server rpcbind
/etc/exports# 格式:目錄 客戶端網段(選項)
# 範例:共享 /share 給 192.168.0.0/24,讀寫
/share 192.168.0.0/24(rw,sync,no_root_squash)
# 共享 /home/dev 給所有 IP,同步寫入,全映射為匿名用戶
/home/dev *(rw,sync,all_squash,anonuid=1000,anongid=1000)
# 共享光碟映像唯讀
/mnt/cdrom 192.168.0.*(ro,sync)
| 類別 | 選項 | 說明 |
|---|---|---|
| 存取權限 | ro | 唯讀 |
| rw | 讀寫 | |
| 用戶映射 | all_squash | 所有用戶映射為匿名 (nfsnobody) |
| no_all_squash | 預設,保留原 UID/GID | |
| root_squash | 預設,root 映射為匿名 | |
| no_root_squash | root 保持 root 權限(危險,僅信任環境用) | |
| anonuid=xxx / anongid=xxx | 指定匿名用戶 UID/GID | |
| 效能/安全 | sync | 同步寫入磁碟,安全但較慢 |
| async | 非同步,快但掉電易丟資料 | |
| wdelay | 預設,延遲寫入合併操作 | |
| no_wdelay | 立即寫入,搭配 sync 用 | |
| subtree_check | 預設,檢查父目錄權限 | |
| no_subtree_check | 不檢查父目錄,提升效能 |
# 啟動 rpcbind (portmap)
systemctl start rpcbind
systemctl enable rpcbind
# 啟動 NFS
systemctl start nfs-server
systemctl enable nfs-server
# 或舊版指令
service rpcbind start
service nfs start
showmount -e localhost
# 或
exportfs -v
# CentOS/RHEL
yum install nfs-utils
# Debian/Ubuntu
apt-get install nfs-common
mkdir -p /mnt/nfs_share
mount -t nfs 192.168.0.1:/share /mnt/nfs_share
# 指定參數
mount -t nfs -o rw,sync,vers=3 192.168.0.1:/share /mnt/nfs_share
/etc/fstab192.168.1.10:/home/dev/share /mnt/nfs1 nfs defaults,_netdev,vers=3 0 0
_netdev:等待網路就緒後再掛載,關鍵參數vers=3:指定 NFSv3(穩定);NFSv4 需配置 idmapdmount | grep nfs
df -h /mnt/nfs_share
ls /mnt/nfs_share
# 內核需啟用 CONFIG_NFS_FS=y, CONFIG_ROOT_NFS=y
# 啟動參數加入:
root=/dev/nfs nfsroot=192.168.1.10:/opt/rootfs ip=dhcp rw
/opt/rootfs/
├── bin, sbin, lib, etc, dev, proc, sys, tmp, var, home, root, mnt
# 使用 buildroot/yocto 生成或手動 debootstrap
firewall-cmd --add-service=nfs --permanent && firewall-cmd --reload;確認 rpcbind 運行;rpcinfo -p server_ip 應見到 nfs、mountd、portmapper。/etc/exports 選項:no_root_squash、anonuid/anongid;服務端目錄實際權限;客戶端 UID/GID 映射。async,no_wdelay,no_subtree_check;網路 MTU 設 9000 (Jumbo Frame);確認磁碟 I/O 無瓶頸。rpc-statd、rpc-lockd 服務運行;NFSv4 需啟用 nfs-idmapd。/etc/exports 限制 IP)sec=krb5p (Kerberos 加密傳輸)