SSH Keepalive and Timeout Settings
Prevent SSH connection drops with ServerAliveInterval and ServerAliveCountMax. Configure client-side keepalive to detect and handle idle timeouts and dead connections.
Detailed Explanation
SSH Keepalive Configuration
SSH connections can be dropped by firewalls, NAT devices, or load balancers that time out idle connections. Client-side keepalive settings prevent this by periodically sending small packets to keep the connection active.
Example Config
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
How Keepalive Works
ServerAliveInterval 60: The client sends a keepalive message every 60 seconds if no data has been exchangedServerAliveCountMax 3: If 3 consecutive keepalive messages receive no response, the client disconnects
With these settings, a dead connection is detected after approximately 180 seconds (3 x 60).
Tuning for Different Scenarios
| Scenario | Interval | Max Count | Timeout |
|---|---|---|---|
| Standard desktop | 60 | 3 | ~3 min |
| Unstable connection | 15 | 5 | ~75 sec |
| Long-running tunnel | 30 | 10 | ~5 min |
| Low-bandwidth link | 120 | 3 | ~6 min |
Aggressive vs Conservative
Aggressive (quick detection, more traffic):
ServerAliveInterval 15
ServerAliveCountMax 3
Conservative (less traffic, slower detection):
ServerAliveInterval 120
ServerAliveCountMax 5
Server-Side Equivalent
The SSH server has similar settings in /etc/ssh/sshd_config:
ClientAliveInterval 60
ClientAliveCountMax 3
TCPKeepAlive vs ServerAliveInterval
SSH has two keepalive mechanisms:
TCPKeepAlive yes(default): Uses TCP-level keepalive. Can be spoofed and doesn't detect application-level issues.ServerAliveInterval: Uses SSH-level encrypted keepalive. More reliable and cannot be spoofed.
Always use ServerAliveInterval instead of relying solely on TCPKeepAlive.
Common Timeout Issues
- Corporate firewalls: Often timeout idle connections after 5-15 minutes
- AWS NAT Gateway: Drops idle connections after 350 seconds
- Cloud load balancers: Typically timeout after 60-300 seconds
Use Case
Anyone who experiences SSH connection drops due to idle timeouts, particularly when working through firewalls, NAT devices, or cloud network infrastructure with aggressive timeout policies.