惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Security Latest
Security Latest
P
Palo Alto Networks Blog
AWS News Blog
AWS News Blog
NISL@THU
NISL@THU
T
Threatpost
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Latest news
Latest news
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
J
Java Code Geeks
P
Privacy International News Feed
阮一峰的网络日志
阮一峰的网络日志
S
Schneier on Security
博客园 - 聂微东
Project Zero
Project Zero
美团技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Scott Helme
Scott Helme
I
Intezer
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hacker News: Front Page
S
Security @ Cisco Blogs
博客园 - 司徒正美
O
OpenAI News
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
SecWiki News
SecWiki News
月光博客
月光博客
S
Security Affairs
The GitHub Blog
The GitHub Blog
P
Privacy & Cybersecurity Law Blog
S
Secure Thoughts
V
V2EX
S
Securelist
F
Fortinet All Blogs
W
WeLiveSecurity
D
Docker
博客园 - 三生石上(FineUI控件)
Simon Willison's Weblog
Simon Willison's Weblog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Webroot Blog
Webroot Blog
Engineering at Meta
Engineering at Meta

Learn Cloud Native

Local development with coding agents on Kubernetes using Signadot | Learn Cloud Native cuenv: one typed file for your whole project | Learn Cloud Native Preflight: AI Code Review Before You Push Anatomy of AI Agents Accessing Google Drive from Next.js Deploying to Fly.io using Dagger and Github Top Cloud-Native & Kubernetes Certifications [2026 Guide] Rapid microservices development with Signadot How to prepare for Istio certified associate exam (ICA) Global Rate Limiting in Istio with Envoy Rate Limit Service My Journey with Istio: From Incubation to Graduation Cilium Network Policy Tutorial: Secure Kubernetes Step by Step Kubernetes Networking: How kube-proxy and iptables Work Istio ServiceEntry: DNS vs. STATIC Resolution & Endpoints Explained Apply an Istio DestinationRule Globally (Mesh-Wide) Istio Rate Limiting: Configure a Local Rate Limiter in Envoy How to expose custom ports on Istio ingress gateway Portainer Tutorial: A Web UI for Kubernetes & Containers Traefik Proxy 2.x and TLS 101 Kubernetes CLI (kubectl) tips you didn't know about Setting up SSL certificates with Istio Gateway ArgoCD Best Practices You Should Know 在 OCI Ampere A1 计算实例上运行 AI Running AI On OCI Ampere A1 Instance How to Deploy Traefik Proxy Using Flux and GitOps Principles Firebase Emulators with Next.js: Local Setup Guide Running Hugo on free Ampere VM (Oracle Cloud Infrastructure) How to use kwatch to detect crashes in Kubernetes clusters Continuous profiling in Kubernetes using Pyroscope Monitoring containers with cAdvisor Creating a Kubernetes cluster in Google Cloud (LAB) Your first Kubernetes Pod and ReplicaSet (LABS) Maybe Convert Wasm Extension Config? GetIstio - CLI, training, and community Attach multiple VirtualServices to Istio Gateway Kubernetes Volumes Explained: Keep Data Beyond the Pod Send a Slack message when Docker images are updated Kubernetes Network Policy Ambassador Container Pattern Start Kubernetes Release Sidecar Container Pattern Kubernetes Init Containers Deploying multiple Istio Ingress Gateways Branch by Abstraction Pattern The Strangler Pattern Kubernetes Development Environment with Skaffold Securing Kubernetes Ingress with Ambassador and Let's Encrypt All About the Ingress Resource How to quarantine Kubernetes pods? Getting started with Kubernetes Horizontal partitioning in MongoDB Docker image tagging scheme Six things to keep in mind when working with Dockerfiles Beginners guide to Docker Beginners guide to gateways and proxies Deploy and Operate Multiple Istio Meshes in one Kubernetes Cluster Managing service meshes with Meshery Circuit Breaking in Istio Explained Build and push your Docker images using Github Actions Kubernetes and Istio service mesh workshop materials Build Netlify-like deployment for React app using Kubernetes pods Six exciting enhancements in Istio 1.4.0 Fallacies of Distributed Systems CAP Theorem Explained Master the Kubernetes CLI (kubectl) - Cheatsheet Minikube Basics and How to Get Started with Kubernetes 5 Tips to Be More Productive with Kubernetes What are sticky sessions and how to configure them with Istio? Debugging Kubernetes applications using Istio Kubernetes Ingress and Istio Gateway Resource Zero Downtime Releases using Kubernetes and Istio Traffic Mirroring with Istio Service Mesh Expose a Kubernetes service on your own custom domain
Container Lifecycle Hooks
Peter Jausovec · 2021-05-03 · via Learn Cloud Native

The concept of hooks is well-known in the tech world. Events usually trigger hooks, and they allow developers to react to those events and run some custom code. Let's take a simple user interface with a button and a text box. There might be multiple events that developers might be interested in handling (i.e., running some code whenever the event happens). One of these events could be the onClick event. You could write an onClick handler that gets called whenever a user clicks a button.

Another popular example of hooks is webhooks. For example, your e-commerce website can define webhooks that can send you a JSON payload with the purchase information to a URL you specified whenever a sale occurs. You write a handler (in this case, it could be a serverless function) and set your serverless function as a handler for an event. This allows you to loosely couple the functionality and handle events that happen on a different system.

Simple Webhook
Simple Webhook

Similarly, Kubernetes provides so-called container hooks. The container hooks allow you to react to container lifecycle events. There are two hooks you can use, the PostStart and PreStop.

Kubernetes executes the PostStart hook as soon as the container is created. However, there's no guarantee that the hook runs before the containers' ENTRYPOINT command is called (they fire asynchronously). Note that if the hook handler hangs, it will prevent the container from reaching a running state.

Kubernetes calls the PreStop hook before a container gets terminated. For the container to stop, the hook needs to complete executing. If the code in the handler hangs, your Pod will remain in the Terminating state until it gets killed.

If either of the hook handlers fails, the container will get killed. If you decide on using these hooks, try to make your code as lightweight as possible, so your containers can start/stop quickly.

As for the handlers, you can use a command that gets executed inside the container (e.g. myscript.sh) or send an HTTP request to a specific endpoint on the container (e.g. /shutdown).

The most common scenarios you'd use the hooks for are performing some cleanup or saving the state before the container is terminated (PreStop) or configure application startup once the container starts (PostStart).

We've talked about init containers, and there are differences between the two:

  • Init containers have their image while lifecycle hooks are executed inside the parent containers
  • Init containers are defined at the Pod level, while lifecycle hooks are defined per each container
  • Init containers are guaranteed to execute before the application containers start, while the PostStart hook might not execute before the ENTRYPOINT is called
Lifecycle hooks
Lifecycle hooks

Let's look at an example to see how these lifecycle handlers work.

apiVersion: v1
kind: Pod
metadata:
  name: hooks-pod
spec:
  containers:
    - name: hooks-pod
      image: kennethreitz/httpbin
      lifecycle:
        postStart:
          exec:
            command:
              ['/bin/sh', '-c', 'echo Hello postStart! > /var/tmp/hello.txt']
        preStop:
          exec:
            command: ['/bin/sh', '-c', 'sleep 10']

In this Pod YAML, we define both hooks. In the postStart hook, we are writing "Hello postStart!" to a file in the container (/var/tmp/hello.txt). The Save the above YAML contents to hooks-pod.yaml and create the Pod:

$ kubectl apply -f hooks-pod.yaml
pod/hooks-pod created

Once the Pod is running, we can check the contents of the hello.txt file inside the container:

$ kubectl exec -it hooks-pod -- cat /var/tmp/hello.txt
Hello postStart!

If you delete the Pod, you will also notice that it takes an extra 10 seconds for Kubernetes to delete it.

How about the preStart hook?

You might be wondering why there's no preStart hook. Even though there's an existing issue opened since 2014 that talks about omplementing the PreStart and PostStop hooks, however, there's no updates on it.

The latest guidance is that if you want to implement a PreStart hook, you should implement it in the init container. To learn how Init containers work, check out the Kubernetes Init Containers blog post.