- How To Mount NFS Share In Linux and Windows?
- Install NFS Server
- Ubuntu, Debian, Mint, Kali Client Packages
- Fedora, CentOS, Fedora Client Packages
- Ubuntu, Debian, Mint, Kali Server Packages
- Fedora, CentOS, Fedora Server Packages
- Check NFS Service Status
- Start NFS Service
- Create NFS Share
- Enable Exports
- Mount NFS Share For Linux
- List NFS Mounts
- Unmount NFS Share For Linux
- Mount NFS Share For Windows
- Как смонтировать общий ресурс NFS в Linux
- Установка клиентских пакетов NFS
- Монтирование файловых систем NFS вручную
- Автоматическое монтирование файловых систем NFS с помощью /etc/fstab
- Размонтирование файловых систем NFS
- Выводы
- Beginners guide to mount NFS share in Linux with examples
- Overview on NFS
- Pre-requisites
- Setup NFS exports Server
- Install NFS Client
- Mount NFS File System manually
- Mount NFS File System Persistently
- Additional Options to mount NFS File System
- Provide NFS version while mounting the NFS File System
- Setting Block Size to Optimize Transfer Speeds
- Removing NFS Mounts from the Client
- How to fix «umount: device is busy»
- Kill the process
- Lazy un-mount
- Conclusion
- Related Posts
How To Mount NFS Share In Linux and Windows?
Network File System or NFS is a network-based filesystem protocol which is mainly used to share files and folders over the network. NFS is a UNIX based technology but can be used by most of the operating systems like Linux, Ubuntu, Debian, Kali, Mint, Fedora, CentOS, RedHat and Windows operating systems Windows 7, Windows 8, Windows 10, Windows Server 2008, Windows Server 2012, Windows Server 2016.
Install NFS Server
NFS packages mainly divided into two parts. First is the server side packages which will install related kernel modules and server tools.
Ubuntu, Debian, Mint, Kali Client Packages
Fedora, CentOS, Fedora Client Packages
Ubuntu, Debian, Mint, Kali Server Packages
After the installation is complete the nfs-server service will be also created automatically.
Fedora, CentOS, Fedora Server Packages
Check NFS Service Status
As the NFS shares will be served over nfs-server we need to the if it is working. We will use systemctl status command with the nfs-server service name.
Check NfS Service Status
We can see that the service is active and working properly.
Start NFS Service
If the service is not started or stopped in any way we need to start the nfs-server service. We will use systemctl start command with the nfs-server service name like below.
Create NFS Share
NFS main configuration is stored in the /etc/exports file. Each share is created line by line. For example, if we want to share /mnt with the IP address 192.168.10.10 we will use the following configuration.
But generally, we share the files and folders with everyone who has access to the NFS server. We can use the following configuration to share everyone.
Enable Exports
After creating the share configuration we need to refresh the NFS table where the shares are stored. We can simply use exportfs command with the -a option which will add current configuration to the NFS table.
Mount NFS Share For Linux
We can use mount command in order to mount NFS share. We will specify the filesystem type as nfs to the mount command with the -t option like below. The server IP address is 192.168.142.144 and share is /mnt . We will mount to the /home/ismail/poftut1 .
List NFS Mounts
After mounting the NFS share we can check it by listing the NFS mount. We will use mount command and filter NFS shares with the grep command like below.
List NFS Mounts
Unmount NFS Share For Linux
We can unmount already mounted NFS shares with the umount command. We will just specify the mount path to the umount command with the sudo command like below.
Mount NFS Share For Windows
First, we will enable NFS modules or features on Windows operating systems. Open Start > Control Panel > Programs. Select Turn Windows Features on or off. Select Services for NFS. Click OK.
We can mount NFS shares in Windows operating systems too. We will use mount command. We will also provide nolock option and other parameters like remote NFS server IP address and local drive which is Z in this case.
Alternatively, we can use net use command which can also mount NFS shares. We will provide the partition name which is z and remote NFS server.
Источник
Как смонтировать общий ресурс NFS в Linux
Сетевая файловая система (NFS) — это протокол распределенной файловой системы, который позволяет вам обмениваться удаленными каталогами по сети. С помощью NFS вы можете монтировать удаленные каталоги в своей системе и работать с удаленными файлами, как если бы они были локальными файлами.
В операционных системах Linux и UNIX вы можете использовать команду mount для монтирования общего каталога NFS в определенной точке монтирования в локальном дереве каталогов.
В этом руководстве мы покажем вам, как вручную и автоматически смонтировать общий ресурс NFS на машинах Linux.
Установка клиентских пакетов NFS
Чтобы смонтировать общий ресурс NFS в системе Linux, сначала необходимо установить клиентский пакет NFS. Название пакета отличается в разных дистрибутивах Linux.
Установка клиента NFS в Ubuntu и Debian:
Установка клиента NFS на CentOS и Fedora:
Монтирование файловых систем NFS вручную
Подключение удаленного общего ресурса NFS аналогично монтированию обычных файловых систем.
Чтобы смонтировать файловую систему NFS в заданной точке монтирования, используйте команду mount в следующей форме:
Выполните следующие действия, чтобы вручную смонтировать удаленный общий ресурс NFS в вашей системе Linux:
Сначала создайте каталог, который будет точкой монтирования для удаленного общего ресурса NFS:
Точка монтирования — это каталог на локальном компьютере, где должен быть смонтирован общий ресурс NFS.
Подключите общий ресурс NFS, выполнив следующую команду от имени пользователя root или пользователя с привилегиями sudo :
Где 10.10.0.10 — это IP-адрес сервера NFS, /backup — это каталог, который сервер экспортирует, а /var/backups — локальная точка монтирования.
В случае успеха вывод не производится.
Если вы хотите указать дополнительные параметры монтирования , используйте параметр -o . Несколько вариантов могут быть представлены в виде списка, разделенного запятыми. Чтобы получить список всех параметров монтирования, введите в терминале man mount .
Чтобы убедиться, что удаленный том NFS успешно смонтирован, используйте команду mount или df -h .
После монтирования общего ресурса точка монтирования становится корневым каталогом смонтированной файловой системы.
Когда вы монтируете общий ресурс вручную, подключение общего ресурса NFS не сохраняется после перезагрузки.
Автоматическое монтирование файловых систем NFS с помощью /etc/fstab
Как правило, вы хотите автоматически монтировать удаленный каталог NFS при загрузке системы.
Файл /etc/fstab содержит список записей, определяющих, где, как и какая файловая система будет монтироваться при запуске системы.
Чтобы автоматически монтировать общий ресурс NFS при запуске системы Linux, добавьте строку в файл /etc/fstab . Строка должна включать имя хоста или IP-адрес сервера NFS, экспортированный каталог и точку монтирования на локальном компьютере.
Используйте следующую процедуру для автоматического монтирования общего ресурса NFS в системах Linux:
Настройте точку монтирования для удаленного общего ресурса NFS:
Добавьте в файл следующую строку:
Где 10.10.0.10 — IP-адрес сервера NFS, /backup — это экспортированный каталог, а /var/backups — локальная точка монтирования.
Выполните команду mount в одной из следующих форм, чтобы смонтировать общий ресурс NFS:
Команда mount прочитает содержимое /etc/fstab и смонтирует общий ресурс.
В следующий раз, когда вы перезагрузите систему, общий ресурс NFS будет смонтирован автоматически.
Размонтирование файловых систем NFS
Команда umount отсоединяет (размонтирует) смонтированную файловую систему от дерева каталогов.
Чтобы отсоединить смонтированный общий ресурс NFS, используйте команду umount за которой следует либо каталог, в котором он был смонтирован, либо удаленный общий ресурс:
Если для монтирования NFS есть запись в fstab , удалите ее.
Команда umount не сможет отсоединить общий ресурс, когда смонтированный том используется. Чтобы узнать, какие процессы обращаются к общему ресурсу NFS, используйте команду fuser :
Как только вы найдете процессы, вы можете остановить их с помощью команды kill и отключить общий ресурс NFS.
Если у вас все еще есть проблемы с —lazy ресурса, используйте параметр -l ( —lazy ), который позволяет вам отключать загруженную файловую систему, как только она больше не занята.
Если удаленная система NFS недоступна, используйте параметр -f ( —force ) для принудительного размонтирования.
Как правило, не рекомендуется использовать опцию принудительного выполнения, так как это может повредить данные в файловой системе.
Выводы
Мы показали вам, как подключать и отключать удаленный общий ресурс NFS. Те же команды применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.
Источник
Beginners guide to mount NFS share in Linux with examples
Table of Contents
In this tutorial I will share the steps to mount NFS share on the client nodes
Overview on NFS
- The Network File System (NFS) is a distributed file system that provides transparent access to remote disks
- Instead of duplicating common directories such as /usr/local on every system, NFS provides a single copy of the directory that is shared by all systems on the network.
- For the user, NFS means that he or she doesn’t have to log into other systems to access files.
- An NFS server is a host that owns one or more filesystems and makes them available on the network;
- NFS clients mount filesystems from one or more servers.
Pre-requisites
Setup NFS exports Server
Configuring NFS Server is not covered as part of this article so I will assume you already a NFS server up and running. In this article we will only cover the NFS client part i.e. to mount NFS share on the client from the server.
In this example I have setup nfs exports on server1 (10.43.138.1) with below configuration
Install NFS Client
The NFS client package will vary based on the Linux distribution.
On Ubuntu install nfs-common
On RHEL/CentOS environment install nfs-utils
Mount NFS File System manually
You can use mount command to mount the NFS file system form remote server to your localhost. The syntax to mount NFS File System on the client node would be:
As per our configuration
- NFS_SERVER is server1 (10.43.138.1)
- /PATH/TO/EXPORTED/DIR is /ISS
- /MOUNT_POINT_ON_CLIENT is /tmp/logs
So to mount NFS manually we will execute below command on the client i.e. server2 (10.43.138.2)
We need the mount point, so I will create the mount point
Next mount the NFS file system from server1 on server2
Verify if the NFS FS is mounted properly
Now based on the permission of your NFS share you can access the data of /ISS from server1 on /tmp/logs on server2
Mount NFS File System Persistently
Now with mount command the changes are not persistent and will not survive a reboot. So if you wish to mount your NFS File System after every reboot then you must add this in /etc/fstab or create a systemd unit file to update fstab during reboot.
In this article we will use our traditional fstab to auto-mount the file system. First of all make sure your mount point exists
Next update /etc/fstab with below content
Save and exit the file.
Next to verify if this is working, first un-mount the NFS File System (if in mounted state)
Now we will use fstab to mount all the FS available in /etc/fstab . You can safely execute this command and it will not break anything in your environment
Now verify if your NFS File System is properly mounted:
That’s it so next time your client reboots, the NFS File System will be automatically mounted as long as your NFS server is up and running.
Additional Options to mount NFS File System
This section will be applicable based on your NFS server configuration.
For example in the above case if I check for the options using which NFS was mounted
Here this command tells us that the NFS was mounted using NFSv4 with different rsize , wsize etc. So while performing the mount we have an option to modify these values.
Provide NFS version while mounting the NFS File System
If your NFS server allows you to choose a NFS version for the client mount then you can use -o nfsvers= , for example to mount using NFSv3
Similarly if your client and server supports you can provide different NFS version.
Setting Block Size to Optimize Transfer Speeds
The mount command options rsize and wsize specify the size of the chunks of data that the client and server pass back and forth to each other. If no rsize and wsize options are specified, the default varies by which version of NFS we are using.
Removing NFS Mounts from the Client
To un-mount the NFS mount point you can just use umount command followed by the mount point path
OR if you are not aware of the mount point you can also provide the REMOTE_SERVER and REMOTE_DIR PATH i.e.
So in our example to un-mount our NFS File System we will use
Next use df or mount command to make sure the NFS FS is not mounted any more.
How to fix «umount: device is busy»
It is possible sometimes you may get this error
This is most likely because the mount_point on which your NFS file system is mounted is in use by some process. So either you can find and kill that process or let the process complete.
Kill the process
To kill the process first you should know the process which is occupying the mount_point . You can use
This will give you the PID of the process using the mount_point in below format, in this example my mount_point is /mnt :
So now you can search for process with PID 12594
Now since you know the process which is occupying your NFS mount point, you can either choose to kill it or let the process complete
You can also use lsof to detect the list of process using a file system:
Lazy un-mount
If you choose to ignore the PID and want to let it complete, how would you know when the process is complete?
You will have to constantly monitor the PID to make sure it is complete after which only you can un-mount your NFS File System. SO to overcome this we have something called lazy un-mount where we can trigger umount with -l or —lazy , for example:
The default umount is not working so let’s try lazy un-mount
The exit status is success so our command was executed successfully:
So this will detach the file system from the file system hierarchy now, and cleanup all references to the file system as soon as it is not busy anymore. The recommended use-case for umount -l is to prevent hangs on shutdown due to an unreachable network share where a normal umount will hang due to a downed server or a network partition.
Conclusion
In this tutorial we learned about methods to mount NFS shares on client nodes. You can use these steps across different Linux distributions such as Red Hat, Fedora, CentOS, SuSE, Ubuntu, Debian etc. The only difference would be the NFS client package to be installed.
Lastly I hope the steps from the article to mount NFS on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник