SSH on a Custom Port in CentOS, Rocky & AlmaLinux: Fixing SELinux Bind Error
Changing the default SSH port 22 inside /etc/ssh/sshd_config looks trivial – until you do it on CentOS, RHEL, Rocky Linux, or AlmaLinux and watch sshd crash on restart with error: bind to port on 0.0.0.0 failed.
The port is completely free, yet journalctl -xeu sshd still reports permission denied. The culprit isn’t your firewall – it’s SELinux, which only permits the SSH daemon to bind to port 22 by default.
2222 or 5522) to stay clear of reserved system ports.
Step 1. Set the New Port in sshd_config
Open /etc/ssh/sshd_config and add or uncomment your chosen port – for example 2222 (during the switch you can temporarily keep both Port 22 and Port 2222, then drop 22 once verified):
Port 2222
If you immediately run systemctl restart sshd without updating SELinux, the daemon exits with status=255 and logs:
error: Bind to port 2222 on 0.0.0.0 failed: Permission denied. fatal: Cannot bind any address.
Step 2. Allow the Port in SELinux Using semanage
The hint is actually printed right inside the comments at the top of sshd_config: register the new port under the ssh_port_t SELinux type. First make sure semanage is installed:
# Rocky Linux / AlmaLinux / RHEL 8 and 9: sudo dnf install policycoreutils-python-utils # CentOS 7: sudo yum install policycoreutils-python
Then register the new port in SELinux and verify it appears in the list:
sudo semanage port -a -t ssh_port_t -p tcp 2222 sudo semanage port -l | grep ssh_port_t
Step 3. Open the Port in firewalld and Restart sshd
Avoid flushing your entire firewall with iptables -F on a live server – add a proper permanent rule in firewalld instead:
sudo firewall-cmd --permanent --add-port=2222/tcp sudo firewall-cmd --reload sudo systemctl restart sshd
Confirm sshd is listening on the new port:
sudo ss -tlnp | grep sshd
Open a new terminal window and test ssh -p 2222 user@server_ip. Once you’re safely logged in on the new port, remove port 22 from firewalld (--remove-service=ssh) and sshd_config.
