Full stack engineer development manual ( author : Luan Peng )
Architecture Series
Be careful :docker Normal exit and abnormal exit will not be initiated automatically SIGTERM,java Normal or abnormal exit ,jvm By the church SIGTERM The signal
docker kill Kill the container process directly
docker stop Send... To the container process SIGTERM The signal , This article introduces the process Capture in the container SIGTERM The signal , Exit gracefully .
github Address :https://github.com/626626cdllp/k8s/tree/master/test/docker-signal
Let's get to know the signal first
Termination of procedure (interrupt) The signal , Type... In the user INTR character ( Usually Ctrl-C) Issued at , Used to notify the foreground process group to terminate the process .
and SIGINT similar , But by QUIT character ( Usually Ctrl-) To control . The process is receiving SIGQUIT Exit will produce core file , In this sense, it is similar to a program error signal .
Program end (terminate) The signal , And SIGKILL The difference is that the signal can be blocked and processed . It is usually used to ask the program to exit normally ,shell command kill This signal is generated by default . If the process doesn't stop , We will try SIGKILL.
stop it (stopped) Process execution . Pay attention to it and terminate as well as interrupt The difference between : The process is not over yet , Just suspended execution . This signal cannot be blocked , To deal with or ignore .
Hypothetical source dockerfile As defined in entrypoint by python /app/server.py
Now you need to rewrite a script entrypoint.sh
#!/bin/sh
# The actual working procedure , Open the general background running situation of the source main program
nohup python /app/server.py &
# Interrupt signal processing function , close python The main program
prog_exit()
{
ps -ef| grep python |grep -v grep |awk '{print $2}'|xargs kill -15
}
# Register interrupt handler
trap "prog_exit" 15
flag=1
# Front end form of running sleep , And cross whether you can exit (python The process no longer exists , Can also be in python Close the container when the process exits by itself )
while [ $flag -ne 0 ];do
sleep 3;
flag=`ps -ef| grep atm |grep -v grep | wc -l`
done;
And then dockerfile Medium entrypoint Start a new script instead
FROM ubuntu:18.04
RUN apt-get update && \
apt-get install -y python3.6 && \
rm -rf /var/lib/apt/lists/*
COPY ./server.py /data/
COPY ./entrypoint.sh /data/
WORKDIR /data/
# Use sh Do elegant exit
ENTRYPOINT ["/data/entrypoint.sh"]
CMD ["bash"]
# Direct to python Initiate an exit order
# ENTRYPOINT ["python3.6","/data/server.py"]
The purpose of graceful exit is to deal with the unfinished business . In general, the exit signal needs to be processed in the business code . Like the one above server.py Add processing logic .
The first way ,
We use ps -ef| grep python |grep -v grep |awk '{print $2}'|xargs kill -15
The command to python The service started kill The signal , We can do it in python This is also received in the script bash Sponsored kill The signal .
The second way ,
We receive container initiated... Directly in the business code SIGTERM The signal ( The method is more direct ), such dockerfile The source entry point is still used in
ENTRYPOINT ["python3.6","/data/server.py"]
For example, we can write server.py
import signal
import time
is_running = True
def sigint_handler(num, stack):
print(num,stack)
print('receive sigint')
global is_running
is_running = False
def sigterm_handler(num, stack):
print(num,stack)
print('receive sigterm')
global is_running
is_running = False
def main():
signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGTERM, sigterm_handler)
signal.siginterrupt(signal.SIGINT, False)
signal.siginterrupt(signal.SIGTERM, False)
while is_running:
print('begin sleep')
# Start your business function
time.sleep(3)
print("prepare exit")
print("sleep 10")
time.sleep(10)
print("exit")
if __name__ == "__main__":
main()
perform python3.6 server.py You'll see a log like this
begin sleep
begin sleep
begin sleep
15 <frame object at 0x2371b18>
receive sigterm
prepare exit
sleep 10
About Go Language to system Signal To deal with , You can refer to 《Go System in Signal Handle 》 One article .
https://tonybai.com/2014/10/09/gracefully-shutdown-app-running-in-docker/
https://blog.csdn.net/zhangpeterx/article/details/89454050
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// import com.lmax.disruptor.LifecycleAware;
// Pay attention to let java Process pid by 1, Otherwise docker stop The signal is not received
public class demo {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Exited!");
}
}));
System.out.println("begin!");
try{
Thread.sleep(1000*60);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Reference resources https://kubernetes.io/zh/docs/concepts/containers/container-lifecycle-hooks/
There are two hooks exposed in the container :
The hook executes immediately after the container is created . however , There is no guarantee that the hook will execute before the container entry point . There are no parameters passed to the handler .
Whether to call this hook immediately before the container terminates , Depending on API Request or manage events , Similar to active probe failure 、 resource preemption 、 Resource competition and so on . If the container is already in a fully terminated or completed state , On the other hand preStop Hook call will fail . It's clogged , It's also synchronous , So it has to be done before the call to delete the container . There are no parameters passed to the handler
k8s Example
# Source: superset/templates/secret.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: python-config
data:
pre_start.py: |-
import time
import os
if __name__=='__main__':
print('pre start process %s.' % os.getpid())
print('end')
time.sleep(10)
print('Process start.')
pre_stop.py: |-
import time
import os
if __name__=='__main__':
print('pre stop process %s.' % os.getpid())
print('end')
print('Process end.')
---
apiVersion: v1
kind: Pod
metadata:
labels:
app: python
name: python-pod
spec:
volumes:
- name: python-configmap
configMap:
name: python-config
items:
- key: pre_stop.py
path: pre_stop.py
- key: pre_start.py
path: pre_start.py
containers:
- command: ['xxxxx','xxxxx']
name: python
workingDir: /
image: xxxxxxxxx
lifecycle:
postStart:
exec:
command: ["/bin/bash","-c","python /pre_start.py >> pre_start.txt"]
preStop:
exec:
command: ["/bin/bash","-c","python /pre_stop.py >> pre_stop.txt"]
volumeMounts:
- name: python-configmap
mountPath: /pre_stop.py
subPath: pre_stop.py
- name: python-configmap
mountPath: /pre_start.py
subPath: pre_start.py
The container can access the hook by implementing and registering its handler . For containers , There are two types of hook handlers available :
about PostStart hook , Container entry point and hook are triggered asynchronously . Both are running , The container just enters running state .
about PreStop hook . If PreStop Hook is suspended during execution ,Pod The stage will remain at Terminating state , And in Pod The end of the terminationGracePeriodSeconds After being killed . in other words PreStop The maximum running time of the hook is terminationGracePeriodSeconds The value of the property configuration .
If PostStart or PreStop Hook failed , It will kill the container .
The hook handler's log will not be in Pod Open in the event . If the handler fails for some reason , It will play an event . about PostStart, This is a FailedPostStartHook event , about PreStop, This is a FailedPreStopHook event . You can run kubectl describe pod <pod_name>
Command to view these events