How I Accidentally Locked Myself Out of SSH After Changing the Port
A classic sysadmin mistake — I changed the SSH port on a remote server without opening it in the firewall first. Here's how I fixed it and the checklist I now follow every time.
r5yn1r4143
2d ago
The Oops Moment
I was hardening a fresh Ubuntu server and decided to change the default SSH port from 22 to 2222. Simple, right? I edited /etc/ssh/sshd_config, changed the port, restarted SSH, and... connection refused.
I had forgotten to update the firewall rules before restarting the SSH service. Classic rookie mistake.
What Went Wrong
Here's exactly what I did (don't do this):
# Edited the SSH config
sudo nano /etc/ssh/sshd_config
Changed: Port 22 → Port 2222
Restarted SSH without updating firewall
sudo systemctl restart sshd
The moment SSH restarted, it stopped listening on port 22 and started on 2222. But UFW (Ubuntu's firewall) was still only allowing port 22. My existing session stayed alive, but as soon as I disconnected, I was locked out.
How I Got Back In
Luckily, I had a few options:
Option 1: Cloud Provider Console
Most cloud providers (AWS, DigitalOcean, Vultr, Linode) offer a web-based console or recovery console. I used DigitalOcean's Droplet Console to log in directly and fix the firewall.Option 2: If You Still Have an Active Session
If you haven't disconnected yet, don't close your terminal! Run these commands immediately:sudo ufw allow 2222/tcp
sudo ufw reload
Then test from a new terminal before closing the old one:
ssh -p 2222 user@your-server-ip
Option 3: Recovery Mode
If you're completely locked out and don't have a console, boot into recovery mode through your hosting provider and mount the filesystem to edit the config back.The Right Way to Change SSH Port
Here's the checklist I now follow every single time:
Step 1: Allow the new port in the firewall FIRST
sudo ufw allow 2222/tcp
sudo ufw reload
Step 2: Edit the SSH config
sudo nano /etc/ssh/sshd_config
Change: Port 2222
Step 3: Restart SSH
sudo systemctl restart sshd
Step 4: Test from a NEW terminal (keep the old one open!)
ssh -p 2222 user@your-server-ip
Step 5: Only after confirming it works, remove the old port
sudo ufw deny 22/tcp
sudo ufw reload
Bonus Tips
sshd -t to test your config before restarting. It catches syntax errors:sudo sshd -t
Key Takeaway
Never restart a network service until you've confirmed the firewall allows the new configuration. Test first, commit second. This applies to SSH, web servers, database ports — anything that listens on a network port.
The order matters: Firewall first, config second, test third, clean up last.
Comments
Sign in to join the discussion.