DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Set Up a NAT Gateway on a Linux VPS

A practical, distribution-aware guide to routing a private subnet through a Linux VPS, with nftables masquerade and SNAT commands, forwarding rules, persistence, testing and fixes for one-way replies.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To use a Linux VPS as a NAT gateway, make four pieces work together: enable IPv4 forwarding, translate the private subnet’s source addresses in a postrouting NAT chain, permit the forwarded traffic in the firewall, and route client traffic and Internet replies through the VPS. The shortest modern implementation uses nftables; masquerade is for a changing public address, while static SNAT is preferable when the VPS has a fixed public address.

What a VPS NAT gateway actually does

A NAT gateway sits between a private network and an Internet-facing interface. A private client sends a packet with a source address such as 10.20.0.15 toward the VPS. The VPS routes that packet out its WAN interface, then changes the source address to the VPS’s public address. Connection tracking records the translation, so the reply can be converted back and delivered to the original client.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Traffic leaving your private network is thus ‘masqueraded’ as having originated from your Ubuntu gateway machine.” — Ubuntu Server documentation, IP masquerading section.

The arrangement is often used for a private subnet, a WireGuard or other tunnel interface, a bridge, or isolated virtual machines. It does not by itself create a private network or assign addresses. Clients still need addresses, a route through the VPS, and a working return path.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
Requirement What it controls Typical failure when missing
IPv4 forwarding Allows the kernel to route packets between interfaces The VPS receives packets but does not pass them onward
Postrouting NAT Rewrites private source addresses for Internet-bound traffic Upstream networks cannot return traffic to unroutable private addresses
FORWARD firewall acceptance Allows transit traffic through the firewall Packets are dropped before the NAT rule can help
Client route Chooses the VPS as the client’s gateway No traffic reaches the VPS at all
Return routing Ensures replies come back through the VPS Outbound packets appear to work, but replies never reach clients

These are separate controls. A correct masquerade rule cannot compensate for disabled forwarding, a dropped FORWARD packet, an incorrect private CIDR, or an asymmetric reply path.

Plan the interfaces and private address range

Do not copy interface names from an example. Cloud VPS images may call the public interface eth0, ens3, or something else. The private side might be a second NIC, a bridge, or a tunnel such as wg0.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. List addresses and interfaces with ip -br address.
  2. Check the VPS’s existing routes with ip route. Identify the default route and its output interface.
  3. Identify the private interface or tunnel through which client packets arrive.
  4. Write down the exact private CIDR, for example 10.20.0.0/24, and the VPS’s private-side address, for example 10.20.0.1.

Keep the source range as narrow as the design permits. A rule for 10.0.0.0/8 can translate unrelated traffic from other internal networks; a rule for the actual client subnet limits accidental NAT. If the VPS has several private networks, create an explicit rule for each intended range rather than using a broad catch-all.

The private clients must either use the VPS as their default gateway or have an explicit route for the destinations that should leave through it. The VPS itself must retain a functioning default route over its public interface; do not replace that route while changing client routing.

Enable IPv4 forwarding permanently

First enable forwarding immediately for the running system, then write the setting to a file so a reboot does not silently disable the gateway. Red Hat’s documented router procedure uses this persistent configuration:

echo "net.ipv4.ip_forward=1" > /etc/sysctl.d/95-IPv4-forwarding.conf
sysctl -p /etc/sysctl.d/95-IPv4-forwarding.conf

Verify the result:

sysctl net.ipv4.ip_forward

The expected value is net.ipv4.ip_forward = 1. If it is 0, packets can arrive on the private interface and still fail before NAT is considered. Check the value again after a reboot as part of operational validation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose one firewall and NAT framework

Modern distributions commonly expose nftables directly. Ubuntu also documents iptables rules through UFW. Both can implement forwarding and NAT, but mixing independently managed legacy iptables and nftables definitions makes it difficult to know which rules are active and can create duplicate or conflicting behavior.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Inspect the current configuration before adding anything:

nft list ruleset
iptables-save

Use the framework that your distribution and existing firewall service already manage. The commands below show a direct nftables implementation. If UFW or another firewall manager owns the ruleset, express the equivalent policy through that manager instead of making an unmanaged parallel ruleset.

Configure outbound NAT with nftables

Create the postrouting NAT chain

Masquerade belongs in a postrouting NAT chain. The nftables documentation describes masquerade as a special case of source NAT, available from Linux kernel 3.18 onward, that derives the source address from the output interface. Create the IPv4 NAT table and chain if they do not already exist:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
nft add table ip nat
nft 'add chain ip nat postrouting { type nat hook postrouting priority 100; policy accept; }'

If the table or chain already exists, the creation command will report an error. That is a signal to inspect and reuse the existing object, not to keep adding copies.

Add a masquerade rule for a dynamic public address

Replace <PRIVATE_CIDR> with the actual client range and <WAN_IF> with the public interface:

nft add rule ip nat postrouting ip saddr <PRIVATE_CIDR> oifname "<WAN_IF>" masquerade

For example, a private range of 10.20.0.0/24 leaving through ens3 would be represented as:

nft add rule ip nat postrouting ip saddr 10.20.0.0/24 oifname "ens3" masquerade

Scoping both the source range and output interface prevents the rule from translating traffic that was not intended to use this gateway. Masquerade is the appropriate choice when the external address can change, because the kernel obtains the current address from the output interface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Use static SNAT when the public address is fixed

If the VPS has a fixed public source address, use explicit SNAT instead:

nft add rule ip nat postrouting ip saddr <PRIVATE_CIDR> oifname "<WAN_IF>" snat to <PUBLIC_IP>

For example:

nft add rule ip nat postrouting ip saddr 10.20.0.0/24 oifname "ens3" snat to 203.0.113.25

Replace the documentation-only address above with the VPS address assigned by your provider. Do not use a source address that is not routed to this VPS. If an address used for translation is not reachable through the NAT box, Internet replies have nowhere to return.

Allow transit traffic in the firewall

NAT is not an authorization policy. A restrictive filter policy still needs explicit FORWARD rules. The following nftables example creates an IPv4/IPv6-capable filter table but limits the transit rules shown here to IPv4 source traffic; adapt the family and policy to the rest of your firewall:

nft add table inet filter
nft 'add chain inet filter forward { type filter hook forward priority filter; policy drop; }'
nft add rule inet filter forward iifname "<PRIVATE_IF>" oifname "<WAN_IF>" ip saddr <PRIVATE_CIDR> ct state new,established,related accept
nft add rule inet filter forward iifname "<WAN_IF>" oifname "<PRIVATE_IF>" ct state established,related accept

Replace <PRIVATE_IF> with the interface that receives client traffic. The first rule permits new connections from the intended private range and their tracked states toward the WAN. The second permits replies that belong to those connections back toward the private side. If an existing forward chain already has a policy and state rule, add only the narrowly scoped rule required for this subnet; do not replace unrelated firewall policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When using UFW or a distribution firewall service, configure the equivalent forward acceptance there. A rule visible in nftables is not proof that a higher-level manager will preserve it across reloads.

Route private clients through the VPS

On every client, set the VPS’s private-side address as the default gateway, or add a route only for the destinations that should use the tunnel. A temporary Linux route looks like this:

ip route replace default via <VPS_PRIVATE_IP> dev <PRIVATE_IF>

Use a more specific route when the VPS should provide access to only selected destinations:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
ip route replace <DESTINATION_CIDR> via <VPS_PRIVATE_IP> dev <PRIVATE_IF>

These commands change the running client and may not survive a reboot. Persist the gateway in the client’s network configuration, cloud-init, NetworkManager profile, systemd-networkd unit, or tunnel configuration according to that client’s operating system. Ensure the client’s address and gateway are on the same reachable private network.

For a tunnel, the peer configuration must also send the intended destination range through the VPS. For a bridged or second-NIC design, the upstream private network must know that the VPS is the next hop. NAT handles address translation; it does not install routes on other machines.

Understand return routing and asymmetric replies

With masquerade or SNAT, the Internet sees the VPS’s public address, so normal Internet replies return to the VPS. The connection-tracking state then reverses the translation and forwards the reply to the private client. This works only when the translated public address is actually assigned or routed to the VPS.

If you translate to a different public address, the network upstream must route that address back to the VPS. Otherwise an outbound packet may leave successfully while its reply goes elsewhere. The same issue appears when a private client has another default gateway: requests can leave through the VPS, but replies or subsequent packets can take a different path. Check both directions rather than treating a successful first packet as proof that routing is correct.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the gateway in a controlled order

  1. Test the client-to-gateway hop. From a client, ping the VPS’s private address or otherwise connect to a service on that address. Failure here indicates addressing, link, tunnel, or client-route trouble, not an Internet NAT problem.
  2. Test the VPS’s own Internet path. From the VPS, verify that its default route and DNS configuration work independently of forwarding.
  3. Test a public destination from a client. Use an IP address first, then a hostname. An IP test separates forwarding/NAT failures from client DNS configuration.
  4. Inspect the active rules and counters. Run nft list ruleset and confirm that the source CIDR and WAN interface exactly match the packet path. Counters on the forward and postrouting rules should increase during a test.
  5. Capture both sides when necessary. A packet capture on the private interface should show the client source address; a capture on the WAN should show the translated source address. Comparing timestamps exposes drops and asymmetric paths.
  6. Check connection tracking for stateful failures. If the first packet leaves but replies are rejected, inspect conntrack state and the established/related return rule.

Do not use a throughput number as a pass/fail criterion: authoritative documentation for this configuration does not establish a universal performance or reliability benchmark. Validate the actual routes, rule matches, and reply path for your VPS and client set.

Troubleshoot the common failure patterns

Symptom Checks Likely correction
The client cannot reach the VPS’s private address Client address, interface state, tunnel/bridge membership, and route Fix the private link or route before changing NAT
The VPS works, but clients cannot reach any public IP sysctl net.ipv4.ip_forward, FORWARD policy, and rule counters Set forwarding to 1 and permit the private-to-WAN flow
Forward counters rise but postrouting counters do not Private CIDR, output interface name, and NAT table family Correct the match so it uses the actual source range and WAN interface
Outbound packets leave, but replies fail Translated source address, upstream route, conntrack state, and WAN capture Use the VPS address for masquerade or ensure the SNAT address routes back to it
Only some destinations work Client route specificity, policy rules, MTU/tunnel settings, and firewall counters Find the destination-dependent route or filtering difference rather than widening NAT blindly
It works until reboot Sysctl file, firewall service, and loaded nftables ruleset after boot Persist both forwarding and firewall configuration with the distribution-supported mechanism
Rules appear duplicated or contradictory nft list ruleset, iptables-save, and the service that owns each ruleset Choose one manager and remove or reconcile unmanaged legacy definitions

A correct POSTROUTING rule cannot fix a packet dropped earlier in the FORWARD chain. Conversely, an accepted forward packet with no matching NAT rule will normally expose a private source address that upstream networks cannot return to.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Make the configuration persistent and auditable

The sysctl file above is already a persistent forwarding configuration. Persist nftables through the firewall service and file format supported by your distribution rather than relying on commands entered interactively. A common workflow is to review the live ruleset, validate a candidate file, and arrange for the distribution’s nftables unit to load it at boot:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
nft list ruleset > /etc/nftables.conf
nft -c -f /etc/nftables.conf

Treat the first command as an example, not a universal installation procedure: it can overwrite an existing policy, and some systems generate rules through another manager. Back up the current configuration, remove rules that should not be retained, and confirm the service that loads the file before enabling it. After a reboot, verify forwarding, the active NAT chain, the filter policy, and the client route.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep an inventory of the private CIDRs, interface names, public addresses, and the service responsible for loading each rule. This makes a later interface rename, provider migration, or firewall reload diagnosable instead of mysterious.

Optionally publish an internal service with DNAT

Outbound NAT is not required to expose an internal service. For inbound publishing, create a prerouting NAT chain and translate only the intended ports to a specific internal host:

nft 'add chain ip nat prerouting { type nat hook prerouting priority -100; policy accept; }'
nft add rule ip nat prerouting iifname "<WAN_IF>" tcp dport { 80, 443 } dnat to <INTERNAL_IP>

The rule must be paired with a filter rule that permits the selected inbound connection and with a valid return path from the internal host. Red Hat’s documented pattern uses masquerade when the external address is dynamic and SNAT when it is static. Do not publish ports merely because DNAT can translate them; expose only services that are intentionally listening, patched, authenticated, and allowed by the security policy.

If the internal host’s default gateway is not the NAT VPS, its replies may bypass the VPS and fail stateful translation. Correct that route or use an appropriate source-NAT design so both directions traverse the gateway.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operational and security safeguards

  • Limit masquerade and forwarding rules to the exact private CIDR and intended interface.
  • Keep a restrictive default forward policy unless the gateway is deliberately an open router.
  • Allow established and related return traffic without permitting arbitrary new inbound connections.
  • Do not confuse a NAT rule with a firewall boundary; NAT changes addresses but does not decide which applications may connect.
  • Record rule counters and review them when investigating unexpected traffic.
  • Do not maintain separate, opaque NAT policies in legacy iptables and nftables without understanding which kernel hooks and service loaders are active.
  • Test recovery after a firewall reload and after a reboot before putting dependent services into production.

Masquerade or SNAT: the practical choice

Situation Use Reason
The VPS’s public address can change Masquerade The source address is derived from the output interface
The VPS has a fixed public address Explicit SNAT The intended source address is unambiguous and statically declared
The translated address is not assigned to the VPS Neither until routing is arranged Upstream replies must route that address back through the NAT box
Inbound port publishing DNAT in prerouting, plus filter and return-path rules Inbound traffic must be translated before routing to the internal host

For a typical single-public-interface VPS with a changing address, the minimal reliable design is therefore: enable forwarding, masquerade the exact private range on the WAN interface, permit new private-to-WAN and established WAN-to-private forwarding, and point clients at the VPS. For a fixed address, replace masquerade with SNAT and verify that the address is routed to the VPS.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.