Setting up a NAT Server in Hetzner Cloud: Step-by-Step Guide

Abstract: Resolves the inability of Hetzner Cloud VMs without public IPs to access the internet by configuring a NAT gateway with private networking and iptables masquerading.

Created: 2026-09-02 by

Configure a NAT server in Hetzner Cloud by enabling Private Networking, assigning private IPs to client VMs, and configuring Ubuntu’s iptables or nftables for masquerading. This setup allows instances without public IPs to route traffic through a designated gateway, ensuring secure and efficient internal communication within your cloud infrastructure.

Prerequisites and Network Architecture

Before deploying the NAT solution, you must understand how Hetzner Cloud handles networking. Unlike traditional on-premise setups where you might plug into a physical switch, Hetzner uses software-defined networking. The critical component here is the Private Net. Without it, your client VMs cannot communicate with each other privately, nor can they use a central node for NAT unless that node has a public IP. You need at least two servers: 1. The NAT Gateway: A server with a public IPv4 address. This will handle the translation of private addresses to its public IP. 2. Client VMs: Servers that do not require direct public internet access. These will rely on the NAT Gateway for outbound connectivity. It is essential to ensure that all participating VMs are located in the same datacenter. Private Networking is only available within specific datacenters and cannot span across regions. If your clients are in different locations, you would need a VPN solution instead, as discussed in Using WireGuard to Establish a Tunnel Between NATted Clients and a Middleman.

Step 1: Enable Private Networking in Hetzner Console

The most common mistake users make is attempting to configure routing before enabling the underlying network interface. You cannot assign private IPs if Private Net is disabled. 1. Log in to the Hetzner Robot or Hetzner Console. 2. Navigate to the Networks section. 3. Click Add Network. 4. Select the datacenter where your VMs reside. 5. Choose a subnet (e.g., 10.0.0.0/24). Ensure this subnet does not conflict with any other networks you may have. 6. Attach the newly created network to both your NAT Gateway and your Client VMs. Once attached, the network appears in the console, but the operating systems inside the VMs do not yet know about it. You must now configure the OS level.

Step 2: Configure Network Interfaces on Ubuntu

Ubuntu 22.04 and later use netplan for network configuration. You need to modify the YAML configuration files to recognize the new private interface. Typically, the primary public interface is named eth0, while the private interface might be named eth1 or similar, depending on the order of attachment. Check your current interfaces using ip addr. Look for an interface with a MAC address matching the one shown in the Hetzner Console under the Private Net details. Edit the netplan configuration file, usually found in /etc/netplan/. Add the following configuration for the private interface. Note that you do not need to define a default gateway for the client VMs; they will receive their routing instructions from the NAT server.
network:
  version: 2
  ethernets:
    eth0:
      dhcp4: true
    eth1:
      dhcp4: false
      addresses:
        - 10.0.0.10/24
      nameservers:
        addresses:
          - 8.8.8.8
          - 1.1.1.1
Apply the changes with sudo netplan apply. Verify connectivity by pinging the NAT Gateway’s private IP from the client VM. For more details on managing these interfaces, refer to How do Ubuntu-server network interfaces work?.

Step 3: Configure IP Forwarding on the NAT Gateway

The NAT Gateway must be configured to forward traffic between its public and private interfaces. First, enable IP forwarding in the kernel. Edit /etc/sysctl.conf and uncomment or add the following line:
net.ipv4.ip_forward = 1
Apply the settings immediately with:
sudo sysctl -p
Verify that forwarding is active by checking the value:
cat /proc/sys/net/ipv4/ip_forward
It should return 1.

Step 4: Set Up Masquerading with iptables

Now you must configure the firewall to perform Network Address Translation. We will use iptables to masquerade traffic coming from the private subnet. Add the POSTROUTING rule to replace the source IP of packets leaving the public interface:
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Here, eth0 is assumed to be the public interface. Adjust this if your public interface has a different name. To ensure these rules persist after a reboot, install iptables-persistent:
sudo apt install iptables-persistent
sudo netfilter-persistent save
Additionally, you must allow forwarding between the interfaces. By default, Ubuntu’s UFW or iptables policy may drop forwarded packets. Allow this explicitly:
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
Save these forwarding rules as well using netfilter-persistent save.

Step 5: Configure Client Routing

Your client VMs now have private IPs, but they do not know how to reach the internet. They need a default route pointing to the NAT Gateway’s private IP. On each client VM, set the default gateway to the NAT Gateway’s private IP address. If you used netplan, update the client configuration:
network:
  version: 2
  ethernets:
    eth0:
      dhcp4: true
    eth1:
      dhcp4: false
      addresses:
        - 10.0.0.11/24
      routes:
        - to: default
          via: 10.0.0.10
      nameservers:
        addresses:
          - 8.8.8.8
In this example, 10.0.0.10 is the private IP of your NAT Gateway. Apply the config with sudo netplan apply. Test the connection by pinging an external IP like 8.8.8.8. If successful, check if DNS works by running curl http://example.com.

Troubleshooting Common Issues

If connectivity fails, check the following: 1. Firewall Rules: Ensure no local firewall on the NAT Gateway is blocking incoming traffic on the private interface. While we allowed forwarding, explicit input policies might still block packets. 2. Hetzner Firewall Scope: Remember that the Hetzner Cloud Firewall applies to public interfaces. It does not inspect private network traffic. Do not try to manage private traffic security through the Hetzner Console firewall. 3. Routing Loops: Ensure your client VMs are not trying to route traffic back out through their own public interface if one exists. Disable public IPs on client VMs if they are strictly for internal NAT usage. For scenarios involving complex routing between multiple VMs, consider reading How to Configure a Traffic Route from VM1 through Host to VM2.

Frequently Asked Questions

Can I use this NAT setup for inbound connections?

No, standard masquerading only supports outbound connections initiated from inside the private network. For inbound traffic, you must set up port forwarding (DNAT) rules in addition to masquerading. This requires modifying the PREROUTING chain in iptables to redirect specific ports to the internal private IP.

Why is my client VM unable to resolve DNS names?

DNS resolution issues often occur because the NAT Gateway is not forwarding DNS queries correctly or the client is not using the right nameserver. Ensure the client VMs have valid nameserver entries in their netplan configuration. Additionally, verify that the NAT Gateway itself has working DNS and that UDP port 53 traffic is allowed through the forwarding rules.

Does this work with IPv6?

This guide focuses on IPv4 NAT, which is necessary because IPv6 typically uses global unique addresses and does not require NAT in the same way. If you need IPv6 connectivity for private clients, you would assign them global IPv6 prefixes and configure static routes instead of using masquerading. Hetzner provides IPv6 ranges by default, so private clients can often communicate directly over IPv6 without a NAT server.

What happens if the NAT Gateway goes down?

If the NAT Gateway fails, all client VMs lose their internet connectivity since they rely on it for routing. There is no automatic failover in this simple setup. To improve reliability, you would need to implement a high-availability cluster using technologies like Keepalived and VRRP, which adds complexity regarding IP management and state synchronization.

Can I connect these private VMs to the internet via a VPN instead?

Yes, if you prefer encryption or need to bridge disparate datacenters. Using WireGuard or OpenVPN allows you to tunnel traffic from private clients through a VPN server. This approach is more secure than plain NAT as it encrypts the traffic, but it introduces overhead. See Routing Traffic Coming to OpenVPN Access Server to the VPN Not Working for troubleshooting VPN-specific routing issues.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More