If you do one thing from this tutorial, do this. Password authentication on a public server is the cause of most compromises, and turning it off takes ten minutes.
Generate a key, on your own machine
# on your laptop, not the server
ssh-keygen -t ed25519 -C "you@example.com"
Accept the default path. Set a passphrase — it encrypts the key on disk, so a stolen laptop is not instantly a stolen server. Your agent will remember it, so you type it once per session.
Ed25519 rather than RSA: shorter, faster, and the current default recommendation.
Create a user to work as
Running everything as root means every mistake is unrecoverable and every compromise is total.
# on the server
adduser deploy
usermod -aG sudo deploy
Copy your key to that user
From your own machine:
ssh-copy-id deploy@YOUR_SERVER_IP
If ssh-copy-id is unavailable, do it by hand on the server:
mkdir -p /home/deploy/.ssh
nano /home/deploy/.ssh/authorized_keys # paste the contents of your .pub file
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh
chmod 600 /home/deploy/.ssh/authorized_keys
Those permissions are not optional. SSH refuses to use a key file that others can read, and does so with an error that does not obviously say so.
Test before you lock the door
This is the step people skip and then lock themselves out.
Open a second terminal — keep your existing root session alive — and connect as the new user:
ssh deploy@YOUR_SERVER_IP
sudo whoami # should print: root
Only once that works do you continue.
Disable passwords and root login
sudo nano /etc/ssh/sshd_config
Set these three:
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
Modern Ubuntu often splits config across /etc/ssh/sshd_config.d/,
and a file there can override what you just set. Check:
sudo grep -r "PasswordAuthentication" /etc/ssh/
Then reload and verify from your still-open session:
sudo systemctl reload ssh
sudo sshd -T | grep -E "permitrootlogin|passwordauthentication"
Open a third terminal and confirm you can still get in. Now close the root session.
Optional: change the port
Moving SSH off 22 stops most automated scanning. It is not security — a determined attacker scans all ports — but it cuts log noise dramatically.
Port 2222
If you do this, open the new port in the firewall before reloading SSH, which is the subject of the next chapter and a classic way to lock yourself out.