These commands apply to Ubuntu with a sudo-capable account. Make an independent backup before changing packages or network rules, and keep your current SSH session open. Check whether you have a working recovery console or another recovery method before enabling a firewall.
Refresh the package index, then review and apply the proposed upgrades. A restart may be required; plan it around your applications and verify that they start afterwards. Do not run unattended destructive package removal commands from an unknown tutorial.
Before enabling UFW, allow the actual SSH TCP port used by this server. The example uses port 22; replace it if your service uses another port. Allow only additional ports required by your application. Open a second SSH connection to test access after changing the rules. If the second connection fails, correct the rules in the existing session before disconnecting.
sudo apt update
sudo apt upgrade
# Replace 22 if SSH uses another port
sudo ufw allow 22/tcp
sudo ufw status verbose
sudo ufw enable
sudo ufw status verbose