- Install NFS Server and Client on Ubuntu
- Setting up the host server
- Step 1: Install NFS Kernel Server
- Step 2: Create the Export Directory
- Step 3: Assign server access to client(s) through NFS export file
- Step 4: Export the shared directory
- Step 5: Open firewall for the client (s)
- Configuring the Client Machine
- Step 1: Install NFS Common
- Step 2: Create a mount point for the NFS host’s shared folder
- Step 3: Mount the shared directory on the client
- Step 4: Test the connection
- Conclusion
- Karim Buzdar
- Установка и настройка NFS-сервера и клиента в CentOS/RHEL
- Установка и настройка NFS-сервера в Linux CentOS
- Настройка клиента NFS в CentOS
- How to Setup NFS (Network File System) on RHEL/CentOS/Fedora and Debian/Ubuntu
- Setup and Configure NFS Mounts on Linux Server
- Setting Up the NFS Server
- Setting Up the NFS Client
- Test the Working of NFS Setup
- Removing the NFS Mount
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Install NFS Server and Client on Ubuntu
NFS or Network File System is a distributed file system protocol originally developed only by Sun Microsystems. Through NFS, you can allow a system to share directories and files with others over a network. By sharing NFS files, users and even programs can access information on remote systems almost as if they were on a local machine.
NFS operates in a client-server environment where the server is responsible for managing the authentication, authorization, and administration of clients, as well as for all data shared within a particular file system. After authorization, any number of clients can access the shared data as if it were in their internal storage. Setting up an NFS server on your Ubuntu system is very easy. You only need to do some necessary installations and configurations, both on the server and on the client machines, and you are ready to go.
In this article we will explain step by step how to set up an NFS server and client that allows you to share files from one Ubuntu system to another.
We have run the commands and procedures described in this article on a Ubuntu 18.04 LTS system and recently tested them with the new Ubuntu 20.04. Since we use the Ubuntu command line, the terminal, to perform all operations, you can open it either by using the system dash or the key combination Ctrl+Alt+T.
Setting up the host server
In order to set up the host system to share directories, we will need to install the NFS Kernel server on it, and then create and export the directories that we want the client systems to access. Please follow these steps in order to smoothly set up the host side:
Step 1: Install NFS Kernel Server
Before installing the NFS Kernel server, we need to update our system’s repository index with that of the Internet through the following apt command as sudo:
The above command lets us install the latest available version of a software through the Ubuntu repositories.
Now, run the following command in order to install the NFS Kernel Server on your system:
The system will prompt you with a Y/n option to confirm if you want to continue with the installation. Please enter Y and then hit Enter to continue, after which the software will be successfully installed on your system.
Step 2: Create the Export Directory
The directory that we want to share with the client system is called an export directory. You can name it according to your choice; here, we are creating an export directory by the name of “sharedfolder” in our system’s mnt(mount) directory.
Use the following command, by specifying a mount folder name according to your need, through the following command as root:
As we want all clients to access the directory, we will remove restrictive permissions of the export folder through the following commands:
Now all users from all groups on the client system will be able to access our “sharedfolder”.
You can create as many sub-folders in the export folder as you want, for the client to access.
Step 3: Assign server access to client(s) through NFS export file
After creating the export folder, we will need to provide the clients the permission to access the host server machine. This permission is defined through the exports file located in your system’s /etc folder. Please use the following command in order to open this file through the Nano editor:
Editing this file needs root access; therefore you will need to use sudo with your command. You can also open the file in any of your personal favorite text editors.
Once you have opened the file, you can allow access to:
- A single client by adding the following line in the file:
- Multiple clients by adding the following lines in the file:
- Multiple clients, by specifying an entire subnet that the clients belong to:
In this example, we are specifying an entire subnet of all the clients we want to grant access to our export folder (sharedfolder):
Add the required line(s) to your exports file and then save it by hitting Ctrl+X, entering Y, and then hitting Enter.
The permissions “rw,sync,no_subtree_check” permissions defined in this file mean that the client(s) can perform:
- rw: read and write operations
- sync: write any change to the disc before applying it
- no_subtree_check: prevent subtree checking
Step 4: Export the shared directory
After making all the above configurations in the host system, now is the time to export the shared directory through the following command as sudo:
Finally, in order to make all the configurations take effect, restart the NFS Kernel server as follows:
Step 5: Open firewall for the client (s)
An important step is to verify that the server’s firewall is open to the clients so that they can access the shared content. The following command will configure the firewall to give access to clients through NFS:
In our example, we are giving access to an entire subnet of clients machines through the following command:
Now when you check the status of your Ubuntu firewall through the following command, you will be able to view the Action status as “Allow” for the client’s IP.
Your host server is now ready to export the shared folder to the specified client(s) through the NFS Kernel Server.
Configuring the Client Machine
Now is the time to make some simple configurations to the client machine, so that the shared folder from the host can be mounted to the client and then accessed smoothly.
Step 1: Install NFS Common
Before installing the NFS Common application, we need to update our system’s repository index with that of the Internet through the following apt command as sudo:
The above command lets us install the latest available version of a software through the Ubuntu repositories.
Now, run the following command in order to install the NFS Common client on your system:
The system will prompt you with a Y/n option to confirm if you want to continue with the installation. Please enter Y and then hit Enter to continue, after which the software will be successfully installed on your system.
Step 2: Create a mount point for the NFS host’s shared folder
Your client’s system needs a directory where all the content shared by the host server in the export folder can be accessed. You can create this folder anywhere on your system. We are creating a mount folder in the mnt directory of our client’s machine:
Step 3: Mount the shared directory on the client
The folder that you created in the above step is like any other folder on your system unless you mount the shared directory from your host to this newly created folder.
Use the following command in order to mount the shared folder from the host to a mount folder on the client:
In our example, we are running the following command to export our “sharedfolder” from the server to the mount folder “sharedfolder_client” on the client machine:
Step 4: Test the connection
Please create or save a file in the export folder of the NFS host server. Now, open the mount folder on the client machine; you should be able to view the same file shared and accessible in this folder.
Conclusion
Setting up an NFS client-server environment on Ubuntu systems is an easy task. Through this article, you learned how to install the required NFS packages on both the server and the clients. You also learned how to configure the NFS server and client machines so that folders can be shared and then accessed smoothly without any firewall or permissions-related glitch. Now you can easily share content from one Ubuntu system to the other using the NFS protocol.
Karim Buzdar
About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn
Установка и настройка NFS-сервера и клиента в CentOS/RHEL
Network File System (NFS) – протокол распределенной файловой системы для организации общего доступа к файлам и папками. За основу в NFS взят протокол удаленных процедур (ONC RPC). NFS позволяет монтировать удаленные файловые системы по сети сеть. В отличии от FTP, NFS позволяет получить доступ только к тем частям файла, к которым обратился процесс. Имейте в виду, что данные в протоколе NFS по умолчанию не шифруются, и аутентификация клиентов не выполняется (доступ ограничивается по IP).
NFS очень прост в настройке, как со стороны сервера, так и со стороны клиента. В данной статье мы рассмотрим установку и настройку NFS-сервера и после чего, подключим NFS ресурс на клиенте. В этой статье для примера использования технологии NFS мы используем CentOS 8. В других Linux дистрибутивах (RHEL, Fedora и т.д.) все действия аналогичны.
Установка и настройка NFS-сервера в Linux CentOS
По умолчанию nfs уже установлен в CentOS 8 с пакетом Standard. Если вы удалили компоненты NFS, или ставили сервер в режиме Minimal Install, можно установить пакет NFS с помощью пакетного менеджера yum (dnf):
# yum install nfs-utils -y
# dnf install nfs-utils -y
У меня пакет уже был установлен:
После установки нужных пакетов, нужно запустить службы nfs-server и rpcbind, добавьте их в автозагрузку:
Если у вас в системе установлен firewalld откройте необходимые порты:
# firewall-cmd —permanent —add-port=111/tcp
# firewall-cmd —permanent —add-port=20048/tcp
# firewall-cmd —permanent —zone=public —add-service=nfs
# firewall-cmd —permanent —zone=public —add-service=mountd
# firewall-cmd —permanent —zone=public —add-service=rpc-bind
# firewall-cmd —reload
# iptables -t filter -A INPUT -p tcp —dport 111 -j ACCEPT
# iptables -t filter -A INPUT -p tcp —dport 2049 -j ACCEPT
# iptables -t filter -A INPUT -p tcp —dport 20048 -j ACCEPT
# service iptables save
# service iptables restart
Теперь создадим директорию, которая будет раздаваться вашим NFS сервером:
# mkdir -p /backup/nfs
# chmod -R 777 /backup/nfs
Теперь в конфигурационном файле с настройками NFS сервера (/etc/exports) нужно опубликовать данный каталог и назначить права доступа.
Добавьте в файл следующую строку для предоставления доступа к NFS всем хостам в указанной IP подсети:
Или можно ограничить доступ для конкретного IP:
Рассмотрим более подробно формат предоставления прав к NFS каталогу:
- rw – права на запись в каталоге, ro – доступ только на чтение;
- sync – синхронный режим доступа. async – подразумевает, что не нужно ожидать подтверждения записи на диск (повышает производительность NFS, но уменьшает надежность);
- no_root_squash – разрешает root пользователю с клиента получать доступ к NFS каталогу (обычно не рекомендуется);
- no_all_squash — включение авторизации пользователя. all_squash – доступ к ресурсам от анонимного пользователя;
- no_subtree_check – отключить проверку, что пользователь обращается в файлу в определенном каталоге (subtree_check – используется по умолчанию);
- anonuid, anongid – сопоставить NFS пользователю/группу указанному локальному пользователю/группе(UID и GID).
Чтобы применить новые настройки NFS каталогов, выполните:
И перезапустите nfs-сервер:
# systemctl restart nfs-server
На этом установка и настройка nfs-сервера закончена и можно приступить к настройке клиента.
Настройка клиента NFS в CentOS
Для настройки NFS клиента, нужно также установить пакет nfs-utils. Для CentOS 7:
# yum install nfs-utils -y
# dnf install nfs-utils -y Добавляем сервисы в автозагрузку и включаем:
# systemctl enable rpcbind
# systemctl enable nfs-server
# systemctl start rpcbind
# systemctl start nfs-server
Теперь на клиенте, нужно создать директорию, в которую мы смонтируем nfs-каталог:
Теперь можно смонтировать удаленное NFS-хранилище командой:
# mount -t nfs 192.168.0.100:/backup/nfs/ /backup
можно принудительно указать версию NFS протокола, которую нужно использовать
# mount -t nfs -o vers=4 192.168.0.100:/backup/nfs/ /backup
Где IP — это адрес NFS-сервера, который вы настроили ранее.
Теперь Теперь в списке перемонтированных разделов диска отображается подключенный NFS ресурс с удаленного сервере. Вы можете читать данные из этого каталога, или записывать в него (в зависимости от прав, которые назначены для вашего IP на NFS сервере). Чтобы NFS каталог автоматически монтировался при перезагрузке, нужно открыть файл fstab:
И добавьте строку:
После сохранения файла fstab, можно применить его командой:
Итак, мы настроили и подключили удаленное NFS хранилище, которое можно использовать для прозрачного сетевого доступа к общему ресурсу с различных хостов. Можно складывать в NFS каталог бэкапы, хранить там файлы ISO образов и т.д.
How to Setup NFS (Network File System) on RHEL/CentOS/Fedora and Debian/Ubuntu
NFS (Network File System) is basically developed for sharing of files and folders between Linux/Unix systems by Sun Microsystems in 1980. It allows you to mount your local file systems over a network and remote hosts to interact with them as they are mounted locally on the same system. With the help of NFS, we can set up file sharing between Unix to Linux system and Linux to Unix system.
Setup NFS Server and NFS Client in Linux
Benefits of NFS
- NFS allows local access to remote files.
- It uses standard client/server architecture for file sharing between all *nix based machines.
- With NFS it is not necessary that both machines run on the same OS.
- With the help of NFS we can configure centralized storage solutions.
- Users get their data irrespective of physical location.
- No manual refresh needed for new files.
- Newer version of NFS also supports acl, pseudo root mounts.
- Can be secured with Firewalls and Kerberos.
NFS Services
Its a System V-launched service. The NFS server package includes three facilities, included in the portmap and nfs-utils packages.
- portmap : It maps calls made from other machines to the correct RPC service (not required with NFSv4).
- nfs: It translates remote file sharing requests into requests on the local file system.
- rpc.mountd: This service is responsible for mounting and unmounting of file systems.
Important Files for NFS Configuration
- /etc/exports : Its a main configuration file of NFS, all exported files and directories are defined in this file at the NFS Server end.
- /etc/fstab : To mount a NFS directory on your system across the reboots, we need to make an entry in /etc/fstab.
- /etc/sysconfig/nfs : Configuration file of NFS to control on which port rpc and other services are listening.
Setup and Configure NFS Mounts on Linux Server
To setup NFS mounts, we’ll be needing at least two Linux/Unix machines. Here in this tutorial, I’ll be using two servers.
- NFS Server: nfsserver.example.com with IP-192.168.0.100
- NFS Client : nfsclient.example.com with IP-192.168.0.101
Installing NFS Server and NFS Client
We need to install NFS packages on our NFS Server as well as on NFS Client machine. We can install it via “yum” (Red Hat Linux) and “apt-get” (Debian and Ubuntu) package installers.
Now start the services on both machines.
After installing packages and starting services on both the machines, we need to configure both the machines for file sharing.
Setting Up the NFS Server
First we will be configuring the NFS server.
Configure Export directory
For sharing a directory with NFS, we need to make an entry in “/etc/exports” configuration file. Here I’ll be creating a new directory named “nfsshare” in “/” partition to share with client server, you can also share an already existing directory with NFS.
Now we need to make an entry in “/etc/exports” and restart the services to make our directory shareable in the network.
In the above example, there is a directory in / partition named “nfsshare” is being shared with client IP “192.168.0.101” with read and write (rw) privilege, you can also use hostname of the client in the place of IP in above example.
NFS Options
Some other options we can use in “/etc/exports” file for file sharing is as follows.
- ro: With the help of this option we can provide read only access to the shared files i.e client will only be able to read.
- rw: This option allows the client server to both read and write access within the shared directory.
- sync: Sync confirms requests to the shared directory only once the changes have been committed.
- no_subtree_check: This option prevents the subtree checking. When a shared directory is the subdirectory of a larger file system, nfs performs scans of every directory above it, in order to verify its permissions and details. Disabling the subtree check may increase the reliability of NFS, but reduce security.
- no_root_squash: This phrase allows root to connect to the designated directory.
For more options with “/etc/exports“, you are recommended to read the man pages for export.
Setting Up the NFS Client
After configuring the NFS server, we need to mount that shared directory or partition in the client server.
Mount Shared Directories on NFS Client
Now at the NFS client end, we need to mount that directory in our server to access it locally. To do so, first we need to find out that shares available on the remote server or NFS Server.
Above command shows that a directory named “nfsshare” is available at “192.168.0.100” to share with your server.
Mount Shared NFS Directory
To mount that shared NFS directory we can use following mount command.
The above command will mount that shared directory in “/mnt/nfsshare” on the client server. You can verify it following command.
The above mount command mounted the nfs shared directory on to nfs client temporarily, to mount an NFS directory permanently on your system across the reboots, we need to make an entry in “/etc/fstab“.
Add the following new line as shown below.
Test the Working of NFS Setup
We can test our NFS server setup by creating a test file on the server end and check its availability at nfs client side or vice-versa.
At the nfsserver end
I have created a new text file named “nfstest.txt’ in that shared directory.
At the nfsclient end
Go to that shared directory in client server and you’ll find that shared file without any manual refresh or service restart.
Removing the NFS Mount
If you want to unmount that shared directory from your server after you are done with the file sharing, you can simply unmount that particular directory with “umount” command. See this example below.
You can see that the mounts were removed by then looking at the filesystem again.
You’ll see that those shared directories are not available any more.
Important commands for NFS
Some more important commands for NFS.
- showmount -e : Shows the available shares on your local machine
- showmount -e: Lists the available shares at the remote server
- showmount -d : Lists all the sub directories
- exportfs -v : Displays a list of shares files and options on a server
- exportfs -a : Exports all shares listed in /etc/exports, or given name
- exportfs -u : Unexports all shares listed in /etc/exports, or given name
- exportfs -r : Refresh the server’s list after modifying /etc/exports
This is it with NFS mounts for now, this was just a start, I’ll come up with more option and features of NFS in our future articles. Till then, Stay connected with Tecmint.com for more exciting and interesting tutorials in future. Do leave your comments and suggestions below in the comment box.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.