Reputation: 14843
I have a scenario where I have a shell script which is run using crond
. I need to exit the container if that particular script fails. Seems like SIGKILL
doesn't work with PID 1.
How do I kill the container process (PID 1) from inside the container using bash/sh shell?
Minimal example -
Dockerfile -
FROM alpine:3.5
ENV LOGS_DIR="/rest/logs/" CRON_LOG_FILE="${LOGS_DIR}/cron.log"
RUN apk add --update python py-pip zip bash && \
pip install awscli && \
mkdir -p ${LOGS_DIR} && \
touch ${CRON_LOG_FILE}
COPY ./lr-s3.sh ./lr-entry.sh ./install_crontab.txt ./files_to_rotate.txt ./
RUN chmod +x /lr-s3.sh /lr-entry.sh && \
crontab install_crontab.txt
ENTRYPOINT ["/lr-entry.sh"]
Entrypoint -
#!/bin/bash
LOGS_DIR="${LOGS_DIR:-/rest/logs}"
CRON_LOG_FILE="${LOGS_DIR}/cron.log"
mkdir -p ${LOGS_DIR}
touch ${CRON_LOG_FILE}
ln -sf /proc/1/fd/1 ${CRON_LOG_FILE}
echo "Cron [Starting]"
exec crond -c /var/spool/cron/crontabs -f -L ${CRON_LOG_FILE} "$@"
Script to run via Cron -
aws s3 cp ${LOGS_DIR}/${FL_NAME} s3://${BKTNAME}/${FL_NAME}
if [ "$?" -ne "0" ]; then
echo "S3 Backup Failed"
pkill crond
exit 1
fi
pkill crond
doesn't work inside the script, it has PID 1.
If container restarts or doesn't exist, we will come to know that there is an issue with the container or the script.
Upvotes: 5
Views: 10440
Reputation: 1826
How do I kill the container process (PID 1) from inside the container using bash/sh shell?
PID 1 is protected, so you can't kill it, but you can setup a signal handler for it:
# somewhere in entrypoint
trap "exit" SIGINT SIGTERM
after that, the process will exit
if you sent a kill -s SIGINT 1
from another process inside the container.
Upvotes: 6