System administrators frequently connect to remote Linux servers using Secure Shell (SSH). When you are actively typing, the connection remains stable. However, if you step away from your desk, switch to another application to read documentation, or simply pause for a few minutes while waiting for a compilation to finish, you may return to find your terminal frozen or displaying the error: Write failed: Broken pipe.
This happens because routers, firewalls, and load balancers are designed to automatically drop TCP connections that have been idle for a certain period of time to save resources. To prevent this, you can configure your SSH client to send a tiny, invisible “heartbeat” signal to the server, keeping the connection alive indefinitely.
How to Configure SSH KeepAlive (Client-Side)
The most robust way to fix this issue is by modifying the SSH configuration file on your local machine (the computer you are connecting from). This ensures that every server you connect to will receive the heartbeat signal.
- Open the terminal on your local Linux or macOS machine.
- You need to edit (or create) the SSH config file located in your user’s home directory. Use Nano (or your preferred text editor):
nano ~/.ssh/config - Add the following two lines to the top of the file:
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
Understanding the configuration:
Host *: This applies the settings to every server you connect to.ServerAliveInterval 60: This is the crucial setting. It instructs your SSH client to send a null packet (a heartbeat) to the server every 60 seconds if you haven’t typed anything. This resets the router’s idle timeout timer.ServerAliveCountMax 3: If the server fails to respond to 3 consecutive heartbeats (meaning the server crashed or your internet physically disconnected), the client will automatically terminate the frozen session rather than hanging forever.
Save the file and exit the editor (in Nano, press Ctrl+O, Enter, then Ctrl+X). The changes take effect immediately for all new SSH connections.
How to Use KeepAlive for a Single Command
If you are working on a borrowed computer or do not want to modify the global configuration file, you can pass the ServerAliveInterval variable directly into your SSH command as a flag.
When connecting, use the -o (option) flag like this:
ssh -o ServerAliveInterval=60 user@remote_server_ip
This will temporarily apply the 60-second heartbeat to that specific connection, ensuring it stays alive while you are reading documentation or taking a break.