Set up a static IP address on Ubuntu 18.04 LTS server

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, December 05, 2019

Follow me on Twitter as @mattiasgeniar

If you’re setting up an Ubuntu 18.04 LTS server, you might want to give it a static IP address instead of one assigned by your router over DHCP.

You can use netplan to configure this and assign the static IP.

Set a static IP using netplan

Make sure you’re root on your server, to make things easier. Now start by opening the following file.

It probably contains a line that says dhcp4: yes. Remove that and copy the dhcp4: no lines and below there.

$ cat /etc/netplan/01-netcfg.yaml
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: no
      addresses: [192.168.126.59/24]
      gateway4: 192.168.126.1
      nameservers:
        addresses: [192.168.126.52]

Note: this is a YAML file. In YAML, the indenting matters! Make sure you use 2 spaces for indenting each stanza/config block.

In the config above I assigned the server a static IP of 192.168.126.59 on a /24 subnet (meaning a netmask of 255.255.255.0) with a single nameserver.

Apply the netplan static IP config

Any error in that file might render you without a working network stack. So it’s safe to first try in debug mode to alert you of any errors.

$ netplan apply --debug

If you get an empty response, everything was OK and your new IP configuration has been applied.

If there was an issue with the YAML syntax or the config, it’ll be printed on-screen.

$ netplan apply --debug
/etc/netplan/01-netcfg.yaml:13:18: Invalid YAML: inconsistent indentation:
      nameservers:

In the example above, find the error on line 13 and fix it.

And you’re done!



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.