How to install XFCE and VNC on a headless Ubuntu 18.04 Server

This week I’ve tested some tutorials on the internet which guide through the installation of VNC. Unfortunately some of them just didn’t work out therefore I’m writing down the current way that works flawlessly.

Prerequisites:
– Freshly installed Ubuntu 18.04 server edition (headless installation – no GUI).
– We assume all commands are typed in a terminal of a standard user – so don’t login as root directly.
– You should know how to use the linux terminal and the text editor nano.

Steps:
1. Let’s ensure we have all updates installed:

sudo apt update
sudo apt dist-upgrade

If you have only a root account available on your system then create a new default user for you:

sudo adduser YOUR_NEW_USER
usermod -a -G sudo YOUR_NEW_USER

2. Install XFCE4 and VNC:

sudo apt install xfce4 xfce4-goodies
sudo apt install tightvncserver

3. Configuring VNC:
Start vncserver, choose a password, no we don’t want a view-only password, and kill it again:
vncsercer
vncserver -kill :1

Backup the configuration file:

mv ~/.vnc/xstartup ~/.vnc/xstartup.bak

Create a new file

nano ~/.vnc/xstartup

and fill it with:

#!/bin/bash
xrdb $HOME/.Xresources
startxfce4 &

and make it executable:
sudo chmod +x ~/.vnc/xstartup

4. Creating a system daemon for autostarting VNC:
Create a new file:
sudo nano /etc/systemd/system/vncserver@.service

and fill it with these lines:
(replace YOUR_USER with your username)
[Unit]
Description=Start TightVNC server at startup
After=syslog.target network.target

[Service]
Type=forking
User=YOUR_USER
Group=YOUR_USER
WorkingDirectory=/home/YOUR_USER

PIDFile=/home/YOUR_USER/.vnc/%H:%i.pid
ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :%i
ExecStop=/usr/bin/vncserver -kill :%i

[Install]
WantedBy=multi-user.target

Tell Ubuntu about the new daemon file, mark it as runnable on boot and start the service:

sudo systemctl daemon-reload
sudo systemctl enable vncserver@1.service
vncserver -kill :1
sudo systemctl start vncserver@1

5. Use a SSH tunnel to connect to your server.
ssh -L 5901:127.0.0.1:5901 -C -N -l USER YOUR_SERVER_IP

6. Voila! Now you can open up a VNC-Viewer and connect locally to localhost:5901. The system will forward this request through the SSH tunnel to the server and the desktop environment (XFCE) will show up. If you are unsatisfied with the screen dimensions just play around with the -geometry parameter in /etc/systemd/system/vncserver@.service.

(7. Recommendation: For some reason the xfce screensaver produces a quite high cpu load (in my case around 36%) even if you are not connected to the server. Therefore just deactivate it in the settings and you’ll save quite much valueable cpu resources.)

Sources:
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-vnc-on-ubuntu-18-04 (thanks a lot to finid and Brian Hogan)