Skip to content

Instantly share code, notes, and snippets.

@mdemblani
Last active August 8, 2018 06:54
Show Gist options
  • Save mdemblani/4ac250a0074da61ab0a1b7ef63ca7a2b to your computer and use it in GitHub Desktop.
Save mdemblani/4ac250a0074da61ab0a1b7ef63ca7a2b to your computer and use it in GitHub Desktop.
Solution for Dockerfile, if image doesnot shutdown on CTRL(CMD)+C

In-case if you run a Docker image and after that you try to kill it, the kill signal is not detected by the Docker container process and in that scenario you have to resort to restarting your Docker process. This is because, the Docker image on which the container is built upon, doesnot detect the Kill Signal i.e. doesnot register any listeners for the kill signal and in this process the signal gets lost whenever fired. Considering on of the most popular Docker Library: mysql also has the same issue.

Issue: Container does not catch signals and exit "Ctrl+C"

In that case you can use the following solution:

  1. Create a file docker-shutdown-patch.sh in the same directory as your Dockerfile
  2. In the Dockerfile, change the EntryPoint and CMD defaults of the image as in the sample Dockerfile.
  3. Build the image and start the container
#!/bin/bash
# A wrapper around /entrypoint.sh to trap the SIGINT signal (Ctrl+C) and forwards it to the mysql daemon
# In other words : traps SIGINT and SIGTERM signals and forwards them to the child process as SIGTERM signals
asyncRun() {
"$@" &
pid="$!"
trap "echo 'Stopping PID $pid'; kill -SIGTERM $pid" SIGINT SIGTERM
# A signal emitted while waiting will make the wait command return code > 128
# Let's wrap it in a loop that doesn't end before the process is indeed stopped
while kill -0 $pid > /dev/null 2>&1; do
wait
done
}
asyncRun /entrypoint.sh $@
FROM mysql:5.7
COPY ./mysql.cnf /etc/mysql/conf.d/default.cnf
ENV MYSQL_ROOT_PASSWORD=root
ENV MYSQL_DATABASE=mydatabase
COPY docker-patch.sh /run.sh
# Entrypoint overload to catch the ctrl+c and stop signals
ENTRYPOINT ["/bin/bash", "/run.sh"]
CMD ["mysqld"]
EXPOSE 3306
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment