dotlinux guide

Setting Up and Using Network File Systems (NFS) on Linux: A Comprehensive Guide

Network File System (NFS) is a distributed file system protocol that allows a user on a client computer to access files over a network as if they were stored locally. Developed by Sun Microsystems in the 1980s, NFS has become a cornerstone of file sharing in Linux and Unix environments due to its simplicity, scalability, and seamless integration with POSIX file system semantics. Whether you’re managing a small home network or a large enterprise infrastructure, NFS enables centralized storage, simplifies file access across multiple machines, and streamlines collaboration. This guide will walk you through the fundamentals of NFS, step-by-step setup procedures for servers and clients, common usage patterns, and best practices to ensure secure, performant, and reliable deployments.

Table of Contents

Understanding NFS

NFS Versions

NFS has evolved through several versions, each introducing improvements in security, performance, and functionality:

VersionRelease YearKey FeaturesUse Case
NFSv21989Original version, 32-bit file sizes, UDP-onlyLegacy systems (rarely used today)
NFSv3199564-bit file sizes, TCP support, asynchronous writesWidely compatible, still common in older setups
NFSv42003Stateful protocol, integrated security (ACL support), single port (2049), Kerberos authenticationModern deployments (recommended for new setups)
NFSv4.12010Session trunking, pNFS (parallel NFS for high-performance storage)Enterprise environments, large-scale storage
NFSv4.22016Sparse files, space reservation, server-side copyAdvanced storage features (e.g., cloud integration)

NFSv4 is the de facto standard today due to its simplified port management (only port 2049/TCP), built-in security, and better performance. This guide focuses on NFSv4 unless noted otherwise.

Key Components

  • NFS Server: Hosts shared directories and serves them to clients via the nfsd daemon.
  • NFS Client: Mounts remote shares and accesses files as if they were local.
  • Exports: Directories on the server explicitly configured to be shared (defined in /etc/exports).
  • RPC (Remote Procedure Call): Underlying protocol for client-server communication (NFSv4 reduces RPC dependency).
  • rpcbind: Maps RPC services to ports (required for NFSv3; optional for NFSv4).

Prerequisites

Before setting up NFS, ensure the following:

  1. Linux Distributions: Any modern Linux distribution (e.g., Ubuntu 20.04+, RHEL 8+, CentOS Stream, Debian 11+).
  2. Network Connectivity: Server and clients must be on the same network with static IP addresses (or DNS-resolvable hostnames).
  3. Packages:
    • Server: nfs-kernel-server (Debian/Ubuntu) or nfs-utils (RHEL/CentOS).
    • Client: nfs-common (Debian/Ubuntu) or nfs-utils (RHEL/CentOS).
  4. Firewall: Open port 2049/TCP (NFSv4) on the server. For NFSv3, additional ports (e.g., 111 for rpcbind) may be required.
  5. Permissions: The server’s exported directories must have read/write permissions for client users (adjust with chmod/chown).

Setting Up an NFS Server

Installing NFS Server Packages

Install the NFS server package for your distribution:

Debian/Ubuntu:

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

RHEL/CentOS:

sudo dnf install -y nfs-utils

Configuring the Firewall

Allow NFS traffic through the firewall. For NFSv4, only port 2049/TCP is needed:

Debian/Ubuntu (using ufw):

sudo ufw allow 2049/tcp
sudo ufw reload

RHEL/CentOS (using firewalld):

sudo firewall-cmd --add-service=nfs --permanent
sudo firewall-cmd --reload

Starting and Enabling NFS Services

Start the NFS server service and ensure it runs on boot:

Debian/Ubuntu:

sudo systemctl start nfs-server
sudo systemctl enable nfs-server

RHEL/CentOS:

sudo systemctl start nfs-server
sudo systemctl enable nfs-server

Verify the service status:

sudo systemctl status nfs-server

Configuring NFS Exports

The /etc/exports file defines which directories the server shares and the clients/options allowed to access them.

The /etc/exports File Syntax

Each line in /etc/exports follows this format:

/directory/to/export client1(options) client2(options) ...

Common Options:

OptionDescription
rwRead-write access (default: ro).
roRead-only access.
syncServer writes changes to disk before acknowledging (slower, safer).
asyncServer acknowledges writes before syncing to disk (faster, risk of data loss).
root_squashMaps client root user to nobody (default; enhances security).
no_root_squashAllows client root to retain root privileges (insecure; avoid in production).
no_subtree_checkDisables subtree validation (improves performance for large exports).
anonuid=UID/anongid=GIDMaps anonymous users to a specific UID/GID (e.g., anonuid=1000).

Exporting Directories

  1. Create a shared directory (e.g., /srv/nfs/shared):

    sudo mkdir -p /srv/nfs/shared
    sudo chmod 777 /srv/nfs/shared  # Adjust permissions as needed
  2. Edit /etc/exports to define the export. Example entries:

    • Export to a single client (e.g., 192.168.1.100) with read-write access:

      /srv/nfs/shared 192.168.1.100(rw,sync,no_subtree_check)
    • Export to a subnet (e.g., 192.168.1.0/24) with read-only access:

      /srv/nfs/docs 192.168.1.0/24(ro,sync,no_subtree_check)
    • Export to all clients (use * cautiously; insecure for public networks):

      /srv/nfs/public *(ro,sync,no_subtree_check)

Exporting Directories

After updating /etc/exports, apply the changes with:

sudo exportfs -a  # Reload all exports

Verify exports:

sudo exportfs -v  # List all exported directories with options

Setting Up an NFS Client

Clients access NFS shares by mounting them locally.

Installing NFS Client Packages

Install client tools to mount NFS shares:

Debian/Ubuntu:

sudo apt install -y nfs-common

RHEL/CentOS:

sudo dnf install -y nfs-utils

Testing Server Connectivity

Verify the client can see the server’s exports:

showmount -e <server-ip-or-hostname>

Example output:

Export list for 192.168.1.50:
/srv/nfs/shared 192.168.1.100
/srv/nfs/docs    192.168.1.0/24

Mounting NFS Shares

Temporary Mounts

Use mount to temporarily mount a share (persists until reboot):

sudo mkdir -p /mnt/nfs/shared
sudo mount -t nfs <server-ip>:/srv/nfs/shared /mnt/nfs/shared

Verify the mount:

df -h | grep nfs  # List mounted NFS shares

Permanent Mounts with /etc/fstab

To mount shares automatically at boot, add an entry to /etc/fstab:

  1. Edit /etc/fstab:

    sudo nano /etc/fstab
  2. Add a line for the NFS share:

    <server-ip>:/srv/nfs/shared  /mnt/nfs/shared  nfs  defaults  0  0
    • defaults: Uses common options (rw, suid, dev, exec, auto, nouser, async).
    • Adjust options (e.g., ro for read-only) as needed.
  3. Test the mount:

    sudo mount -a  # Mounts all entries in /etc/fstab

Automounting NFS Shares with autofs

autofs mounts shares on demand (when accessed) and unmounts them after inactivity, reducing network load.

Installing and Configuring autofs

Step 1: Install autofs

# Debian/Ubuntu
sudo apt install -y autofs

# RHEL/CentOS
sudo dnf install -y autofs

Step 2: Configure the Master Map (/etc/auto.master)

Add a line to define a mount point and a secondary map file:

sudo nano /etc/auto.master

Add:

/mnt/nfs /etc/auto.nfs  --timeout=60
  • /mnt/nfs: Base directory for autofs mounts.
  • /etc/auto.nfs: Secondary map file defining shares.
  • --timeout=60: Unmounts inactive shares after 60 seconds.

Step 3: Configure the Secondary Map (/etc/auto.nfs)

Define shares in /etc/auto.nfs:

sudo nano /etc/auto.nfs

Add:

shared  -rw,sync,no_subtree_check  <server-ip>:/srv/nfs/shared
docs    -ro,sync                   <server-ip>:/srv/nfs/docs
  • shared: Subdirectory under /mnt/nfs (e.g., /mnt/nfs/shared).
  • Options and server/share path follow.

Step 4: Restart autofs

sudo systemctl restart autofs

Test by accessing the share (it mounts automatically):

ls /mnt/nfs/shared  # Triggers mount

Common NFS Operations

Unmounting a Share

sudo umount /mnt/nfs/shared  # For temporary/fstab mounts
# autofs unmounts automatically after timeout

Refreshing Exports (Server)

sudo exportfs -ra  # Reloads and updates all exports

Checking NFS Statistics

nfsstat  # Shows NFS server/client statistics

Finding Mounted NFS Shares

mount | grep nfs

Best Practices

Security

  • Use NFSv4: Avoid NFSv3 due to weaker security and port complexity.
  • Limit Clients: Restrict exports to specific IPs/subnets (never use * in production).
  • Enable root_squash: Prevents client root from gaining elevated privileges.
  • Encrypt Traffic: Use VPNs (e.g., WireGuard) or NFSv4 with Kerberos for sensitive data (see Red Hat’s Kerberos guide).
  • File Permissions: Set server export directories to 755 (read/execute for others) to avoid permission issues.

Performance

  • Use sync Over async: Prioritize data integrity unless speed is critical.
  • Disable subtree_check: Improves performance for large or deeply nested exports.
  • Tune Network: Use 10Gbps+ networks for high-throughput workloads; enable jumbo frames.
  • Separate NFS Traffic: Isolate NFS on a dedicated VLAN/subnet to avoid congestion.

Reliability

  • Static IPs: Use static IPs for servers/clients to prevent mount failures.
  • Monitor Services: Use tools like prometheus + node_exporter to track NFS server health.
  • Backup Exports: Regularly back up /etc/exports to avoid losing configuration.
  • Test Failover: For critical systems, use clustered NFS (e.g., GlusterFS, Ceph) for high availability.

Troubleshooting Common Issues

Mount Fails with “Connection Refused”

  • Check Firewall: Ensure port 2049/TCP is open on the server.
  • Verify Exports: Run sudo exportfs -v on the server to confirm the share is exported.
  • Network Issues: Use ping <server-ip> and telnet <server-ip> 2049 to test connectivity.

Permission Denied Errors

  • Root Squash: If the client root can’t write, root_squash is active (default). Use anonuid/anongid to map to a privileged user:
    # In /etc/exports:
    /srv/nfs/shared 192.168.1.100(rw,sync,anonuid=1000,anongid=1000)
  • Server Directory Permissions: Ensure the exported directory on the server has read/write permissions for nobody (or the anonuid user):
    sudo chown -R nobody:nogroup /srv/nfs/shared
    sudo chmod -R 775 /srv/nfs/shared

Slow Performance

  • Switch to async: Temporarily test with async to see if speed improves (balance with data safety).
  • Network Latency: Use tcpdump or iftop to check for network bottlenecks.
  • Block Size: Mount with a larger block size (e.g., mount -t nfs -o rsize=32768,wsize=32768 ...).

Conclusion

NFS is a powerful tool for sharing files across Linux networks, enabling centralized storage and seamless collaboration. By following this guide, you’ve learned to set up an NFS server, configure exports, mount shares on clients, and adopt best practices for security, performance, and reliability.

Whether for home labs or enterprise environments, NFSv4’s simplicity and robustness make it a top choice for networked storage. Experiment with autofs for dynamic mounting and explore advanced features like Kerberos authentication to harden your deployment further.

References