Linux & servers

Why does my background job stop when I close SSH?

Short answer

Putting a command in the background does not make it independent of your SSH session. For a persistent worker, use a service manager; for a one-off task, choose a suitable detached session or nohup setup.

What changes the answer

  • Whether the task is one-off or persistent
  • Terminal input and output dependencies
  • How the process should restart after failure

The ampersand only backgrounds the command

Adding & returns control to your shell while the command runs. It does not provide a restart policy, useful logging or a guarantee that the process will survive the session ending. Shell behaviour, hangup signals and terminal connections can all affect what happens next.

That is why a worker may appear healthy while your SSH window is open, then disappear after you close it.

Choose the right home for the job

For a one-off import, a terminal multiplexer can let you detach and return to the session. nohup can also help a command survive a hangup signal, with suitable input and output redirection. Neither approach makes the application recover automatically from a crash or a server reboot.

For a queue worker or other long-running application service, use a service manager such as systemd. It can define how the process starts, which account runs it, where its logs go and when it should restart. The restart policy still needs to suit the application; a command that exits because of bad configuration should not endlessly repeat useful-looking startup messages.

Recreate the working environment deliberately

A service does not automatically inherit the environment of your interactive shell. Check the executable path, working directory, required environment values and file permissions. Run it as the appropriate application user rather than using root to work around permission errors.

Before launching another copy, check whether the original job is still running. A lost SSH connection does not always mean the process stopped. Starting the same importer twice can duplicate work or make two processes compete for the same queue.

For recurring tasks, also decide what should happen if the previous run is still active. Process supervision and scheduling solve different problems; a reliable setup needs both decisions to be explicit.