Вы запустите скрипт bash в качестве основного скрипта, как показано ниже
exit_script() {
echo "Printing something special!"
touch /data/shutdown.txt
}
echo "Started with $@ $$ $? $0"
echo "Setting up firewall rules"
#if you use bash then below trap command will work
#trap exit_script SIGINT SIGTERM SIGHUP SIGQUIT SIGABRT SIGKILL
# if you use sh then below trap will work
trap exit_script INT TERM HUP QUIT ABRT KILL
tail -f /dev/null &
wait $!
echo "The command has ended now"
Вы можете увидеть вывод, как показано ниже
$ docker run -it -d -v $PWD/data:/data exit
30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67
$ docker stop 30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67
30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67
$ docker logs 30e90fc4b6d6e83b39ec3489a52082ba1b4057016149c4f1b21d8cfc18d68e67
Started with 1 0 /tmp/run.sh
Setting up firewall rules
Printing something special!
The command has ended now
$ ls -al data/
total 0
drwxr-xr-x 1 vagrant vagrant 96 May 27 2018 .
drwxr-xr-x 1 vagrant vagrant 192 May 27 2018 ..
-rw-r--r-- 1 vagrant vagrant 0 May 27 04:13 shutdown.txt
С docker-compose
ниже работал для меня
version: "3"
services:
firewall:
build: .
container_name: firewall
network_mode: host
privileged: true
stdin_open: true
stop_signal: SIGTERM
stop_grace_period: 10s
tty: true
volumes:
- ./data:/data
И тест
$ rm -rf data/
$ docker-compose up --build
Building firewall
Step 1/3 : FROM ubuntu:xenial
---> 0b1edfbffd27
Step 2/3 : COPY run.sh /tmp/run.sh
---> Using cache
---> c4ef587c94e1
Step 3/3 : CMD exec /tmp/run.sh
---> Using cache
---> 89a57a78369e
Successfully built 89a57a78369e
Successfully tagged exitscript_firewall:latest
Starting firewall ... done
Attaching to firewall
firewall | Started with 1 0 /tmp/run.sh
firewall | Setting up firewall rules
^CGracefully stopping... (press Ctrl+C again to force)
Stopping firewall ... done
$ ls -al data/
total 0
drwxr-xr-x 1 vagrant vagrant 96 May 27 2018 .
drwxr-xr-x 1 vagrant vagrant 192 May 27 2018 ..
-rw-r--r-- 1 vagrant vagrant 0 May 27 04:19 shutdown.txt
Вы не увидите вывод в логах, но команды будут выполнены, как вы можете видеть существование shutdown.txt