Will a query which may take hours to execute keep executing on remote server if I close the connection after executing the command?
If I connect to a remote database server via ssh, start mysql client and execute a query which may take a couple of hours to execute, then close the connection, will the query continue to execute until completed? Can I mysqldump in this way on a huge database, go back a few days later and expect it all to be complete?
thanks!
Solution 1:
Simply put: no - unless you take special measures, any long lived commands on the server will terminate when the shell that ssh
started remotely exits. That shell will exit if you terminate your ssh
session, or even if the TCP connection is broken (lose network connectivity, switch wifi networks, hibernate, etc).
However, there are several options to accomplish those "special measures". From simplest to most complex/involved:
-
nohup - simply prepend your one-line command with
nohup
. This works if you can assume that the command will execute and then terminate itself. Output will be sent to thenohup.out
file in your current directory. Example:nohup sh -c "sleep 5; echo done" &
-
screen -
screen
will setup a virtual terminal window that will not exit when yourssh
connection terminates. You can reconnect to the server at a later time and see the status of any commands you were running and issue new commands. Example:% client: ssh server # server: screen # server[0]: mysql -e 'really long query' <disconnect>
The later come back and:
% client: ssh server # server: screen -RD # -RD says "reconnect to my previous screen, even it already attached" # server[0]: <right where you left off in the previous screen>
There are lots of options to
screen
, you can create several "terminals" inside of onescreen
session, and you can configure it extensively in the file~/.screenrc
. mosh - a replacement for
ssh
which will maintain the session regardless of network connectivity. As you migrate between wifi networks, or even hibernate/awaken your machine,mosh
will reconnect to the server. Additionally, it will provide a lag free interface to work through, so as you type your commands, you not be affected by link or server slowness. Note that mosh usesssh
to establish the initial connection and setup the UDP server on the remote end.