先通过Dockerfile创建一个image
vim Dockerfie
<<<< 内容如下:
FROM centosRUN sed -i -e "s|mirrorlist=|#mirrorlist=|g" /etc/yum.repos.d/CentOS-*
RUN sed -i -e "s|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g" /etc/yum.repos.d/CentOS-*
RUN yum install -y net-tools telnet wget vimRUN echo "alias ll='ls -al'" >> /etc/profileRUN mkdir -p /install/java
RUN cd /install/java && wget https://download.java.net/java/GA/jdk22.0.1/c7ec1332f7bb44aeba2eb341ae18aca4/8/GPL/openjdk-22.0.1_linux-x64_bin.tar.gz
RUN cd /install/java && tar zxvf openjdk-22.0.1_linux-x64_bin.tar.gz
RUN echo 'export JAVA_HOME=/install/java/jdk-22.0.1' >> /etc/profile
RUN echo 'export PATH=$JAVA_HOME/bin:$PATH' >> /etc/profileRUN mkdir -p /app
COPY target/myWeb-1.0-SNAPSHOT.jar /app/myWeb-1.0-SNAPSHOT.jarRUN echo '#!/bin/bash' >> /app/startup.sh
RUN echo 'source /etc/profile' >> /app/startup.sh
RUN echo 'exec java -jar /app/myWeb-1.0-SNAPSHOT.jar' >> /app/startup.sh
RUN chmod +x /app/startup.shENTRYPOINT ["/app/startup.sh"]
>>>>
注意Dockerfile文件里面的【RUN echo ‘exec java -jar /app/myWeb-1.0-SNAPSHOT.jar’ >> /app/startup.sh】这句话,里面的【exec】非常重要,没有exec的话虽然也能运行,但做不到优雅关闭。因为exec的作用是让【java】进程成为【pid=1】的进程,如果没有【exec】,【pid=1】的进程是ENTRYPOINT里面的【/app/startup.sh】。
创建镜像
docker build -t my-web .
上传镜像到镜像库
docker tag my-web:latest 192.168.44.228:5000/my-web:latest
docker push 192.168.44.228:5000/my-web:latest
基于该镜像创建pod
kubectl run my-web --image=192.168.44.228:5000/my-web
连接上这个pod看下是否在运行
kubectl attach my-web
删除这个pod试试
kubectl delete pod my-web
可以看到当k8s删除一个pod的时候容器里面的进程收到了【SIGTERM】信息,所以程序里面注册的【ShutdownHook】被触发了,该【ShutdownHook】的注册代码如下:
@SpringBootApplication()
public class MyWebTest {public static void main(String[] args) {registerHook();SpringApplication.run(MyWebTest.class, args);}private static void registerHook() {Runtime.getRuntime().addShutdownHook(new Thread(() -> {// 当pod关闭的时候会触发这个回调System.out.println(LocalDateTime.now() + "-->Hook.run 1....");// 关闭spring bootShutdownHelper.shutdown();System.out.println(LocalDateTime.now() + "-->Hook.run 2....");}));}
}
关于spring boot的优雅关闭请参考【https://blog.csdn.net/chenhz2284/article/details/139359172?spm=1001.2014.3001.5502】