Skip to content

LinuxGuide

How to Set a Static IP on Ubuntu Server With Netplan

  • Updated
  • 11 min read
  • VPS Lane Engineering
Short answer

Create a YAML file in /etc/netplan/ with the interface, address, default route and DNS, then apply it with sudo netplan try.

How we tested this

Ubuntu 24.04.5 LTS, netplan.io 1.1.2, systemd 255.4 (networkd and resolved), iproute2 6.1.0, OpenSSH 9.6p1. Commands were run as root in a systemd container on a virtual Ethernet interface, with netplan try run over a real SSH session. Not run: a reboot, the cloud-init step, and IPv6 at runtime because the test kernel had no IPv6, so the IPv6 file was only validated with netplan generate. Ubuntu 26.04 LTS was not tested.

Static IP on Ubuntu Server at a Glance

A static IP on Ubuntu Server comes down to one YAML file and the short list of commands in this table.

In full, you create a YAML file in /etc/netplan/ that names the network interface and sets dhcp4: false, the IP address with its prefix, the default gateway and the DNS servers. You validate it with sudo netplan generate, apply it with sudo netplan try, and press Enter to keep it only after confirming that network access still works.

Ubuntu Server static IP configuration steps
StepCommandWhy
1. Find the interfaceip -br linkThe name in the file must match the real interface
2. Note current settingsip -4 addr, ip -4 route, resolvectl dnsAddress, prefix, gateway and DNS to copy
3. Back upsudo cp -a /etc/netplan /root/netplan-backupYour way back if the change goes wrong
4. Write the filesudo nano /etc/netplan/99-static.yamlAddress, default route and DNS servers
5. Validatesudo netplan generateCatches YAML and key errors without touching the network
6. Apply with a safety netsudo netplan tryRolls back unless you press Enter within the timeout
7. Verifyip -4 addr, ip -4 route, ping, resolvectl queryProof that address, route and DNS all work

These steps were tested on Ubuntu Server 24.04.5 LTS with the default networkd renderer. Ubuntu 26.04 LTS is also available, but nothing here was run on it, so this guide does not claim it behaves the same. On any other release, run sudo netplan generate before you apply anything to see whether that version accepts the file. Ubuntu 18.04 does not accept to: default and needs the older gateway4 key instead. Ubuntu Desktop normally hands the network to NetworkManager, which is a different workflow.

Before you start you need sudo rights, the address details from your provider or network admin, and a second way in such as the provider console. Every address in this guide, such as 203.0.113.10 and 2001:db8:113::10, is a documentation example. Replace them with your own.

Static IP or DHCP Reservation

A static IP set in Netplan is not the same thing as a DHCP reservation, and the reservation is often the simpler choice.

Choosing between a reservation and a Netplan static address
SituationBetter choiceWhy
Home or office network where you control the routerDHCP reservationThe router keeps handing the server the same address and nothing changes on the server
VPS or dedicated server where the provider tells you to configure the addressNetplan static addressThe address has to be set on the server itself
No DHCP server on the networkNetplan static addressNothing else can hand out the address
The server must keep its address even if DHCP is downNetplan static addressThe address no longer depends on a lease

If you go static, use an address that is assigned to you or sits outside the DHCP pool. An address that looks unused is not proof that it is free.

Find the Network Interface Name and Current Settings

Find the network interface name first, because Netplan quietly ignores a file written for a name that does not exist.

bash
ip -br link
Output
lo               UNKNOWN        00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP> 
enp1s0@if2       UP             52:54:00:3a:9c:10 <BROADCAST,MULTICAST,UP,LOWER_UP>

Ignore lo. The other line is the interface, here enp1s0. Common names on servers are eth0, ens3 and enp1s0, and the right one is whatever your own output shows.

Now read the address, the routes and the DNS servers the server is using at the moment.

bash
ip -4 addr show dev enp1s0
ip -4 route
resolvectl dns enp1s0
Output
2: enp1s0@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link-netns gw
    inet 203.0.113.10/24 metric 100 brd 203.0.113.255 scope global dynamic enp1s0
       valid_lft 113sec preferred_lft 113sec
default via 203.0.113.1 dev enp1s0 proto dhcp src 203.0.113.10 metric 100 
203.0.113.0/24 dev enp1s0 proto kernel scope link src 203.0.113.10 metric 100 
203.0.113.1 dev enp1s0 proto dhcp scope link src 203.0.113.10 metric 100 
Link 2 (enp1s0): 203.0.113.1

The word dynamic and the proto dhcp routes show this address came from DHCP. A static configuration requires you to enter these network settings manually.

Values to collect before you write the file
ValueWhere it showsExample here
Interface nameip -br linkenp1s0
Address and prefixthe inet line203.0.113.10/24
Default gatewaythe default via line203.0.113.1
DNS serversresolvectl dns203.0.113.1

On a VPS, keep the address the provider assigned and only make it static. Picking a different address in the same range can collide with another customer, and many providers filter traffic from addresses they did not assign. If the provider panel lists different values from the ones DHCP gave you, trust the panel and ask support when unsure.

Check Which Netplan File Configures the Interface

Check which Netplan file configures the interface today, because your new settings are merged with it.

bash
ls -l /etc/netplan/
sudo netplan get
Output
total 4
-rw------- 1 root root 65 Nov 26 03:06 50-cloud-init.yaml
network:
  version: 2
  ethernets:
    enp1s0:
      dhcp4: true

The file name depends on how the server was installed, so yours may differ. netplan get prints the merged result of all files, which is the configuration Netplan actually uses.

Netplan reads YAML files from /lib/netplan/, /etc/netplan/ and /run/netplan/ and merges files with different names in alphabetical order. A later single value replaces an earlier one, but lists are joined together. So dhcp4: false in 99-static.yaml overrides an earlier dhcp4: true, while addresses, routes and DNS servers from the earlier file stay in the merged result.

Stop cloud-init From Rewriting the File

On cloud images, cloud-init can write the Netplan file itself, so stop it from rewriting the file if yours is named after it.

bash
sudo nano /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg
yaml
network:
  config: disabled

This follows the cloud-init documentation and was not run in the test container, which has no cloud-init. A server without the /etc/cloud folder does not need this step. With a separate 99-static.yaml your settings still win the merge for single values, but disabling it removes the chance of cloud-init adding addresses back.

Back Up the Netplan Folder Before Any Change

Back up the Netplan folder before any change, so a rollback is one copy command away.

bash
sudo cp -a /etc/netplan /root/netplan-backup
ls -l /root/netplan-backup
Output
total 4
-rw------- 1 root root 65 Nov 26 03:06 50-cloud-init.yaml

Use a folder name that does not exist yet, otherwise cp nests the copy inside the old one. Then open the provider console once and confirm you can log in there with a password. A backup helps only if you can still reach a shell to restore it.

Write the Netplan Static IP File

Write the Netplan static IP file with four things in it, which are DHCP off, the address, the default route and the DNS servers.

bash
sudo nano /etc/netplan/99-static.yaml
yaml
network:
  version: 2
  ethernets:
    enp1s0:
      dhcp4: false
      addresses:
        - 203.0.113.10/24
      routes:
        - to: default
          via: 203.0.113.1
      nameservers:
        addresses:
          - 203.0.113.1
          - 203.0.113.2
What each key in the file does
KeyMeaningCommon mistake
enp1s0The interface name from the first stepA wrong name is accepted and then does nothing
dhcp4: falseStops asking DHCP for an IPv4 addressLeaving it true keeps the DHCP address as well
addressesThe address with its prefix lengthLeaving out /24 is an error
routes with to: defaultThe default gatewayUsing the deprecated gateway4 key
nameserversDNS servers for this interfaceIndenting addresses level with nameservers

Indent with spaces only, two per level, and keep one space after each colon. Then restrict the file to root. The Netplan documentation recommends mode 600 for its files, because they can hold secrets such as Wi-Fi passwords, and Netplan warns about anything more open.

bash
sudo chmod 600 /etc/netplan/99-static.yaml

Validate the File With netplan generate

Validate the file with netplan generate, which parses every file and writes the backend config without changing the live network.

bash
sudo netplan generate
sudo netplan get
Output
network:
  version: 2
  ethernets:
    enp1s0:
      addresses:
      - "203.0.113.10/24"
      nameservers:
        addresses:
        - 203.0.113.1
        - 203.0.113.2
      dhcp4: false
      routes:
      - to: "default"
        via: "203.0.113.1"

If netplan generate prints nothing and exits without an error, the files passed validation. Read any warnings it does print, because some, such as the conflicting default route warning, still exit with status 0. The merged view should show dhcp4: false, one address and one default route. A clean parse does not prove the values are right. A wrong gateway or a wrong interface name parses fine, which is what the next step protects against.

When the file is wrong, the error names the file, the line and the column. These messages came from the test server, shortened to the part that matters.

Netplan validation errors and their causes
Message from netplan generateCauseFix
Invalid YAML: tabs are not allowed for indentA tab character in the indentationReplace tabs with spaces
Invalid YAML: inconsistent indentationA key sits one space off its siblings, or a colon has no space after itLine the key up and write dhcp4: false
expected mapping (check indentation)A block such as routes is indented under the wrong parentMove it under the interface name
address '203.0.113.10' is missing /prefixlengthNo prefix after the addressWrite 203.0.113.10/24
unknown key 'adresses'A misspelled keyCorrect the spelling
gateway4 has been deprecated, use default routes insteadThe old gateway key, a warning onlyUse routes with to: default
Permissions for ... are too openThe file is readable by other users, a warning onlyRun chmod 600 on it
Conflicting default route declarations for IPv4Two IPv4 default routes use the same routing table and metricRemove the duplicate, give one a different metric, or use separate routing tables with routing-policy

Apply the Static IP Safely With netplan try

Apply the static IP with netplan try, which rolls the network back unless you confirm in time.

bash
sudo netplan try
Output
Do you want to keep these settings?


Press ENTER before the timeout to accept the new configuration


Changes will revert in 114 seconds
Configuration accepted.

This output came from a real SSH session to the test server. The countdown line rewrites itself each second, starting from the default of 120 seconds, and Enter was pressed at 114. Change the wait with --timeout, for example sudo netplan try --timeout 60.

If the new configuration breaks your connection, you cannot press Enter, so Netplan attempts to restore the previous network settings. In the test, changing the address to one the SSH client could not reach froze the session for the full timeout. It then printed Reverting. and carried on in the same session.

The Ubuntu 24.04 manual page for netplan try says the caveats of netplan apply around virtual devices also apply here, and tells you to verify that the configuration has in fact been reverted after a timeout or a cancel. Treat netplan try as a strong safety net that lowers the risk, not as a promise. Before pressing Enter, open a second SSH session to prove new logins work, since the session you are in could survive a change that blocks fresh ones.

Try a Candidate File Outside the Folder

To try a candidate file without leaving it in the folder after a rollback, keep it elsewhere and pass it with --config-file.

bash
sudo netplan try --config-file /root/99-static.yaml

In the test, a rollback left /etc/netplan/ exactly as it was. After pressing Enter, the file was kept under a name with a timestamp in it, such as 99-static.1795662520.2220943.yaml, so rename it to something tidy with sudo mv afterwards.

Set a Rollback Timer for netplan apply

Set a rollback timer when you must use netplan apply, for example in a script, because apply has no rollback of its own.

bash
sudo systemd-run --unit=netplan-rollback --on-active=5min --timer-property=AccuracySec=1s /bin/sh -c "rm -f /etc/netplan/99-static.yaml; cp -a /root/netplan-backup/. /etc/netplan/; netplan apply"
sudo netplan apply
Output
Running timer as unit: netplan-rollback.timer
Will run service as unit: netplan-rollback.service

The timer restores the backup after five minutes unless you cancel it. In the test, a wrong gateway was applied and the timer put the DHCP setup back on its own. Without the AccuracySec setting, systemd timers may fire up to a minute late by default. Once you have confirmed the server is reachable, cancel the timer.

bash
sudo systemctl stop netplan-rollback.timer

Check it is gone with systemctl list-timers netplan-rollback.timer, which should list 0 timers. The timer only covers the next few minutes on a running system, so do not count on it across a reboot.

Verify the Static IP Address Route and DNS

Verify the static IP address, the route and the DNS servers one by one, because each can fail on its own.

bash
ip -4 addr show dev enp1s0
ip -4 route
resolvectl dns enp1s0
Output
2: enp1s0@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link-netns gw
    inet 203.0.113.10/24 brd 203.0.113.255 scope global enp1s0
       valid_lft forever preferred_lft forever
default via 203.0.113.1 dev enp1s0 proto static 
203.0.113.0/24 dev enp1s0 proto kernel scope link src 203.0.113.10 
Link 2 (enp1s0): 203.0.113.1 203.0.113.2

Three differences confirm that the static configuration is active. The word dynamic is gone and the lifetime reads forever, the default route says proto static instead of proto dhcp, and both DNS servers are listed. Now test that packets and names actually flow.

bash
ping -c 3 203.0.113.1
resolvectl query example.com
Output
PING 203.0.113.1 (203.0.113.1) 56(84) bytes of data.
64 bytes from 203.0.113.1: icmp_seq=1 ttl=64 time=0.034 ms
64 bytes from 203.0.113.1: icmp_seq=2 ttl=64 time=0.049 ms
64 bytes from 203.0.113.1: icmp_seq=3 ttl=64 time=0.041 ms

--- 203.0.113.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2042ms
rtt min/avg/max/mdev = 0.034/0.041/0.049/0.006 ms
example.com: 203.0.113.80                                   -- link: enp1s0

-- Information acquired via protocol DNS in 1.3ms.
-- Data is authenticated: no; Data was acquired via local or encrypted transport: no
-- Data from: network

The lab DNS server answers example.com with a documentation address, so your result will differ. Some gateways do not answer ping at all, so a failed ping with working internet access is not a fault by itself.

On your own server, add one test the isolated lab could not run, a ping to a public address you trust to answer, which checks the path beyond the gateway without involving DNS.

bash
ping -c 3 1.1.1.1

If the gateway answers but this does not, look at provider routing, an upstream firewall or outbound filtering. If this works and names still fail, the problem is DNS.

These checks prove the address, the route and DNS work from the server outward right now. They do not prove the server is reachable from the internet, that a firewall allows your traffic, or that the settings survive a reboot. Open a new SSH session from your own computer to cover the first two.

Check the Settings After a Reboot

Check the settings after a reboot only at a quiet time and with provider console access ready, because a reboot was not part of this test.

bash
sudo reboot

After you reconnect, run the same checks again.

bash
ip -4 addr show dev enp1s0
ip -4 route
resolvectl dns enp1s0
sudo netplan get

Confirm that the static address is still assigned, the default route is present, the DNS servers are listed and no DHCP address has come back next to it.

DNS on Ubuntu Server goes through systemd-resolved, and /etc/resolv.conf is a link to its stub file that lists 127.0.0.53. Leave that file alone and set DNS in Netplan, because hand edits there are not the supported way to configure it.

Routes for a Gateway Outside the Subnet

Routes for a gateway outside the subnet need one more key, which matters on providers that hand out a single /32 address.

yaml
      addresses:
        - 203.0.113.10/32
      routes:
        - to: default
          via: 203.0.113.1
          on-link: true

With a /32 prefix the interface has only a host route and no ordinary connected subnet, so the gateway is not automatically treated as directly reachable. on-link: true tells the routing configuration to treat the gateway as directly reachable through this interface. After applying it, the test server showed this route and could ping the gateway.

bash
ip -4 route
Output
default via 203.0.113.1 dev enp1s0 proto static onlink

Check ip -4 route every time you change the prefix on a live interface. In one test run that switched from /24 to /32 with netplan apply, the default route was missing until sudo systemctl restart systemd-networkd was run. Use netplan try for this change so a missing route rolls back.

Avoid two default routes with the same IP family, routing table and metric. Netplan reported those as Conflicting default route declarations in the test, yet still exited with status 0, so read the warnings and not just the exit code. Giving each route its own metric cleared the warning, and setups that route through several interfaces use separate tables with routing-policy.

Add a Static IPv6 Address in the Same File

Add a static IPv6 address in the same file by listing it next to the IPv4 one and giving it a default route of its own.

yaml
network:
  version: 2
  ethernets:
    enp1s0:
      dhcp4: false
      dhcp6: false
      accept-ra: false
      addresses:
        - 203.0.113.10/24
        - 2001:db8:113::10/64
      routes:
        - to: default
          via: 203.0.113.1
        - to: default
          via: 2001:db8:113::1
      nameservers:
        addresses:
          - 203.0.113.1
          - 2001:db8:113::1

This file passed netplan generate on the test server and produced one IPv4 and one IPv6 default route in the networkd config. It could not be applied there, because the test kernel had IPv6 switched off, so no runtime output is shown.

accept-ra: false stops the server from also taking addresses and routes from router advertisements. Only set it when your provider gives you a fixed IPv6 gateway. If the provider expects router advertisements, leave that line out. Verify with the IPv6 versions of the same checks.

bash
ip -6 addr show dev enp1s0
ip -6 route show default
ping -6 -c 3 2001:db8:113::1

Move to a Different IP Address Over SSH

To move to a different IP address over SSH, add the new address next to the old one first instead of swapping them.

Before adding another address, confirm that your provider has assigned it to this server or that your network admin has reserved it. Do not pick an arbitrary address from the subnet, since a provider will not necessarily route it to you. Keep the existing address active until the new one has been applied and tested through a separate SSH connection.

yaml
    enp1s0:
      dhcp4: true
      addresses:
        - 203.0.113.20/24

With DHCP left on and one static address listed, the test server held both addresses at once. Your session on the old address stays up while you check the new one.

Safe order for moving to a new address
StepWhat to doWhy
1Add the new address and keep the old oneNothing is taken away yet
2Run sudo netplan try and confirmBoth addresses are live
3Open a new SSH session to the new addressProof that it is routed to you
4Update DNS records and firewall rules that name the old addressOther systems follow the move
5Remove the old address or set dhcp4: false, then run netplan try from the new sessionThe old address goes last

Roll Back a Lockout From the Console

To roll back a lockout, log in through the provider console, which does not depend on the network settings inside the server.

bash
sudo rm -f /etc/netplan/99-static.yaml
sudo cp -a /root/netplan-backup/. /etc/netplan/
sudo netplan apply
ip -4 addr show dev enp1s0

In the test this brought the DHCP address and its default route back within a few seconds. If you have no backup, delete or fix the file you added and run sudo netplan apply. If the console login itself is not possible, many providers offer a rescue mode where you can mount the disk and edit the files under its etc/netplan folder.

Static IP problems and where to look
What you seeLikely causeFix
No error, but the address did not changeInterface name in the file does not matchCompare with ip -br link and correct the name
Old DHCP address still listed next to the new onedhcp4 is still true in the merged configCheck sudo netplan get and set dhcp4: false
Address is right but nothing beyond the subnet answersWrong or missing default routeCheck ip -4 route and the via address
Ping by address works, names do not resolveWrong or missing DNS serversCheck resolvectl dns enp1s0 and the nameservers block
Settings come back after a reboot on a cloud imagecloud-init wrote its network file againDisable its network config as shown above
SSH froze during netplan tryThe new settings cut your pathWait for the rollback, then fix the file before anything else
Reachable from the server out, not from the internet inProvider routing or a firewall, not NetplanUse the assigned address and check firewall rules
Connection drops now and then, or duplicate address warningsAnother device is using the same addressCheck DHCP reservations and address assignments, then use an address that is assigned to you

For a server where you manage Netplan directly with root access and a recovery console, see Ubuntu VPS hosting.

Questions people ask

How do I set a static IP on Ubuntu Server?

Write the address, default route and DNS servers in a YAML file in the Netplan folder, then run sudo netplan try. Press Enter only when the connection still works.

Where is the Netplan config file on Ubuntu Server?

Netplan files live in /etc/netplan/ and end in .yaml. The file name varies by install method, so list the folder and run sudo netplan get to see the merged result.

What is the difference between netplan try and netplan apply?

Both apply the configuration, but netplan try rolls back unless you confirm within a timeout, 120 seconds by default. Use apply at the console or with a rollback timer.

Is gateway4 still valid in Netplan?

It still parses on Ubuntu 24.04 but prints a deprecation warning. Use a routes entry with to: default and via instead. Ubuntu 18.04 is the exception and needs gateway4.

How do I set DNS servers with a static IP on Ubuntu Server?

Add a nameservers block with an addresses list under the interface in the Netplan file. Check the result with resolvectl dns and do not edit /etc/resolv.conf by hand.

How do I temporarily change an IP address on Ubuntu Server?

Run sudo ip addr add 203.0.113.20/24 dev enp1s0 with an address assigned to your server. It is temporary. In the test, the next netplan apply removed it, and a reboot also clears it, so use Netplan for a permanent address.

Do I need to reboot after changing the IP with Netplan?

No. netplan try and netplan apply change the running network. A later reboot at a quiet time is still a useful test that the settings persist.

How do I go back to DHCP on Ubuntu Server?

Remove the static file or set dhcp4: true and delete the address, route and DNS lines, then run sudo netplan try. The server asks DHCP for an address again.

Sources

  1. Ubuntu 24.04 manual page, netplan try
  2. Netplan documentation, YAML configuration reference
  3. Netplan documentation, netplan generate
  4. Netplan documentation, netplan apply
  5. Netplan documentation, Security
  6. Ubuntu Server documentation, Configuring networks
  7. cloud-init documentation, Network configuration
  8. systemd documentation, systemd.timer
  9. systemd documentation, systemd-run

Written and tested by VPS Lane EngineeringWe run every step on real servers before publishing and update the guide when the software changes.