How to kill/stop remote Docker container after disconnecting SSH

Viewed 2154

I have a remote docker container that I access over SSH. I start the container normally with the docker start command.

sudo docker start 1db52045d674
sudo docker exec -it 1db52045d674; bash

This starts an interactive tty in the container, which I access over ssh. I'd like the container to kill itself if I close the SSH connection. Is there anyway to do this?

3 Answers

.bash_logout is executed every time you use exit command to end a terminal session.

So you can use this file to run the docker stop command when you exit the ssh connection on the remote server.

  1. Create ~/.bash_logout file if not existing.
  2. Add following command to stop the docker container in this file. Example :
    docker stop container_name

Note: If a user closes the terminal window instead of writing the exit command, this file is not executed.

I was hoping for a more elegant solution but in the end I launched a bash script over ssh to trap for a SIGHUP something like:

trap 'docker stop CONTAINER_NAME' SIGHUP;
while sleep 5;
do echo "foo";
done;

so when the operator closes the SSH connection, the trap gets trigger and docker nicely stops

You can use the --init parameter for initializing. This way, your container will be able to take over the init process and you can send a kill signal to it: https://docs.docker.com/engine/reference/run/#specify-an-init-process

Start the server:

docker run --init \
  -p 2222:2222 \
  -e USER_NAME=user \
  -e USER_PASSWORD=pass \
  -e PASSWORD_ACCESS=true \
  -e SUDO_ACCESS=true \
  linuxserver/openssh-server

Just note the --init and -e SUDO_ACCESS=true parameters here.

In another (client) shell,

  1. ssh into container:
$  ssh user@127.0.0.1 -p 2222 -oStrictHostKeyChecking=accept-new
Warning: Permanently added '[127.0.0.1]:2222' (ECDSA) to the list of known hosts.
user@127.0.0.1's password: 
Welcome to OpenSSH Server

2a. send kill signal to PID1 (docker-init):

$ sudo kill -s SIGINT 1
[sudo] password for user: 
$ Connection to 127.0.0.1 closed by remote host.
Connection to 127.0.0.1 closed.

Container is gone.

I hope this helps.

Related