C.W.K.
Stream
Lesson 06 of 12 · published

KeepAlive

~15 min · keepalive, server-alive, nat-timeout, frozen-session

Level 0Pinger
0 XP0/101 lessons0/12 achievements
0/150 XP to next level150 XP to go0% complete

Why SSH sessions die quietly

An idle SSH connection can vanish without warning. NAT tables expire, firewalls drop idle TCP, your laptop goes to sleep — any of these can leave SSH thinking the session is alive while the path is dead. The next time you type a key, the session hangs forever or eventually times out with a confusing error.

ServerAliveInterval — proactive keepalive

Setting ServerAliveInterval 60 tells SSH to send an encrypted keepalive packet every 60 seconds. ServerAliveCountMax 3 says "if 3 in a row get no response, give up and disconnect cleanly." Together — keepalives every minute, and a clean disconnect after 3 minutes of silence instead of an indefinite hang.

The keepalive packets are tiny. The cost is negligible. Always set this in Host *. There's no scenario where you want SSH to silently freeze.

Server-side equivalent

The server has the mirror directives in /etc/ssh/sshd_config: ClientAliveInterval and ClientAliveCountMax. They do the same thing from the server's point of view — useful for kicking out clients that lost connectivity (otherwise their PTYs stick around forever).

Code

Set keepalive globally·ssh-config
# In ~/.ssh/config — applies to every host
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
Server-side mirror·bash
# /etc/ssh/sshd_config
ClientAliveInterval 60
ClientAliveCountMax 3

# Validate and restart
sudo sshd -t
sudo systemctl restart sshd

# macOS: toggle Remote Login off/on in System Settings

External links

Exercise

Add ServerAliveInterval 60 and ServerAliveCountMax 3 to the Host * block in your ~/.ssh/config. Then SSH into a remote machine, leave the session idle for a minute, and run a command — it should work instantly because the keepalives held the path open. Without those directives, an idle session over NAT tends to freeze.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.