Skip to content

Instantly share code, notes, and snippets.

@odg0318
Last active March 27, 2020 02:50
Show Gist options
  • Select an option

  • Save odg0318/d9aa13d89a07e540b6b70ea400a9bd16 to your computer and use it in GitHub Desktop.

Select an option

Save odg0318/d9aa13d89a07e540b6b70ea400a9bd16 to your computer and use it in GitHub Desktop.
Right use entrypoint and cmd in Dockerfile
FROM alpine:3.11
COPY entrypoint.sh /entrypoint.sh
COPY process.sh /process.sh
RUN chmod +x /entrypoint.sh /process.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["/process.sh"]
#!/bin/sh
set -e
trap handle_trap INT
function handle_trap() {
echo "trapped in entrypoint.sh"
exit 1
}
echo "begin entrypoint.sh"
exec "$@"
# the following line will be not executed.
echo "end entrypoint.sh"
$ docker build -t test .
$ docker --rm run test
begin entrypoint.sh
begin process.sh
Mem: 711664K used, 1055120K free, 16888K shrd, 2108K buff, 403816K cached
CPU: 0% usr 0% sys 0% nic 100% idle 0% io 0% irq 0% sirq
Load average: 0.03 0.05 0.06 1/173 6
PID PPID USER STAT VSZ %VSZ CPU %CPU COMMAND
6 1 root R 1580 0% 0 0% top
1 0 root S 1572 0% 0 0% {process.sh} /bin/sh /process.sh
waiting for process(pid=$PID)
trapped in process.sh
#!/bin/sh
set -e
trap handle_trap INT
function handle_trap() {
echo "trapped in process.sh"
kill -TERM $PID
wait $PID
exit 1
}
echo "begin process.sh"
# make a child process of process.sh
top &
PID=$!
echo "waiting for process(pid=$PID)"
wait $PID
# the following line will be not executed.
echo "end process.sh"
@odg0318
Copy link
Author

odg0318 commented Feb 13, 2020

Description

List type of ENTRYPOINT is recommended in Dockerfile.
An example like above can be received INT signal from docker command.

Flow

  1. /entrypoint.sh /process.sh is executed in a container.
  2. /process.sh is executed by exec command with the same pid as /entrypoint.sh, which makes /process.sh receive kill signals.
  3. top is executed on the background and /process.sh waits for its exiting.
  4. Container receives INT kill signal by ctrl+c, which is trapped in /process.sh.
  5. handle_trap function finally kills top process and /process.sh also exits.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment