[英]How do I kill the container process (PID 1) from inside the container using bash/sh shell
I have a scenario where I have a shell script which is run using crond
. 我有一个场景,其中有一个使用crond
运行的shell脚本。 I need to exit the container if that particular script fails. 如果该特定脚本失败,则需要退出容器。 Seems like SIGKILL
doesn't work with PID 1. 似乎SIGKILL
不适用于PID 1。
How do I kill the container process (PID 1) from inside the container using bash/sh shell? 如何使用bash / sh shell从容器内部杀死容器进程(PID 1)?
Minimal example - 最小的例子-
Dockerfile - 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 - 通过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. pkill crond
在脚本中不起作用,它具有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. 如果容器重新启动或不存在,我们将知道容器或脚本存在问题。
How do I kill the container process (PID 1) from inside the container using bash/sh shell? 如何使用bash / sh shell从容器内部杀死容器进程(PID 1)?
PID 1 is protected, so you can't kill it, but you can setup a signal handler for it: PID 1受保护,因此您不能杀死它,但是可以为其设置信号处理程序:
# 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. 之后,如果您从容器内的另一个进程发送了kill -s SIGINT 1
,则该进程将exit
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.