# 如何通过NFS共享文件

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/10276.html | 发布：2022-09-20 | 更新：2022-09-20 | 分类：IDC云库

本指南说明如何通过网络在服务器之间共享文件。NFS 代表网络文件系统，可用于通过附加的文件系统在本地访问远程服务器的数据。

本指南说明如何通过网络在服务器之间共享文件。NFS 代表网络文件系统，可用于通过附加的文件系统在本地访问远程服务器的数据。此示例由 2 台服务器组成，其中一台将充当主机 (storage1)，第二台将充当客户端 (storage2)，文件系统将从主机附加到该客户端。

 

![如何通过NFS共享文件](https://www.mfisp.com/wp-content/uploads/2022/09/39a9ef20a97d73b4542f9dbf411b64aa.png)

 

连接到主机和客户端并安装 nfs-utils 包。

 

## CentOS 上的 NFS：

 

```
[root@storage1 ~]# yum -y install nfs-utils
[root@storage2 ~]# yum -y install nfs-utils
```

 

## Ubuntu/Debian 上的 NFS：

 

```
[root@storage1 ~]# yum -y install nfs-common
[root@storage2 ~]# yum -y install nfs-common
```

 

创建一个将与客户端-服务器共享的目录。如果已经创建，则跳过此步骤。

 

```
[root@storage1 ~]# mkdir -p /home/data
```

 

为共享文件夹分配权限和所有权。

 

```
[root@storage1 ~]# chmod -R 755 /home/data/
[root@storage1 ~]# chown nfsnobody:nfsnobody /home/data/
```

 

## 启动 NFS 服务

 

```
[root@storage1 ~]# systemctl enable rpcbind
[root@storage1 ~]# systemctl enable nfs-server
创建了从 /etc/systemd/system/multi-user.target.wants/nfs-server.service 到 /usr/lib/systemd/system/nfs-server.service 的符号链接。
[root@storage1 ~]# systemctl enable nfs-lock
[root@storage1 ~]# systemctl enable nfs-idmap
[root@storage1 ~]# systemctl start rpcbind
[root@storage1 ~]# systemctl start nfs-server
[root@storage1 ~]# systemctl start nfs-lock
[root@storage1 ~]# systemctl start nfs-idmap
```

 

通过编辑文件 /etc/exports 定义将与哪个客户端共享的文件夹

 

```
[root@storage1 ~]# vi /etc/exports
```

 

在这种情况下，文件的内容将如下所示，其中 181.215.247.22 是客户端-服务器公共 IP 地址。

 

```
/home/data 181.215.247.22(rw,sync,no_root_squash)
```

 

重新启动 NFS 服务。

 

```
[root@storage1 ~]# systemctl restart nfs-server
```

 

在客户端-服务器中选择共享文件夹将被挂载的目录或创建一个新文件夹。

 

```
[root@storage2 ~]# mkdir -p /home/mystorage/
```

 

将文件系统从主机附加到客户端。

 

```
[root@storage2 ~]# mount -t nfs 2.58.28.45:/home/data /home/mystorage/
```

 

检查文件系统是否附加成功。

 

```
[root@storage2 ~]# df -h
已使用的文件系统大小可用使用百分比已安装在
devtmpfs 185M 0 185M 0% /dev
tmpfs 209M 0 209M 0% /dev/shm
tmpfs 209M 8.8M 200M 5%/运行
tmpfs 209M 0 209M 0% /sys/fs/cgroup
/dev/sda1 10G 2.0G 8.1G 20% /
tmpfs 42M 0 42M 0% /run/user/0
2.58.28.45:/home/data 10G 2.1G 8.0G 21% /home/mystorage
```

 

我们在主机服务器中有一个文本文件：

 

```
[root@storage1 ~]# cat /home/data/file.txt
此文本文件存在于 storage1 中
```

 

现在可以在客户端-服务器中本地访问它：

 

```
[root@storage2 ~]# cat /home/mystorage/file.txt
此文本文件存在于 storage1 中
```

 

为了在客户端-服务器重新启动后保持文件系统挂载，在文件 /etc/fstab 底部添加以下行，其中 2.58.28.45 是主机服务器公共 IP 地址。

 

```
2.58.28.45:/home/data /home/mystorage nfs 默认 0 0
```

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
