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

推荐订阅源

T
Troy Hunt's Blog
Last Week in AI
Last Week in AI
D
DataBreaches.Net
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyberwarzone
Cyberwarzone
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
月光博客
月光博客
博客园 - 司徒正美
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
Simon Willison's Weblog
Simon Willison's Weblog
The Register - Security
The Register - Security
T
The Blog of Author Tim Ferriss
V
V2EX
F
Fortinet All Blogs
AWS News Blog
AWS News Blog
T
Tor Project blog
V
Vulnerabilities – Threatpost
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
小众软件
小众软件
L
Lohrmann on Cybersecurity
量子位
F
Full Disclosure
H
Hackread – Cybersecurity News, Data Breaches, AI and More
I
Intezer
NISL@THU
NISL@THU
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 三生石上(FineUI控件)
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
N
Netflix TechBlog - Medium
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
J
Java Code Geeks
S
Schneier on Security

Posts on Noah Bailey

How to turn anything into a router Deploy to Cloudfront from GitHub using OpenID Connect Backup Postgres databases with Kubernetes CronJobs The spelling error made 200 billion times a day You've just bought a new domain. Now what? Who Sawed My Motherboard??? Linux on the P8 Aliexpress Mini Laptop Recovering Mysql/Mariadb after a nasty crash Using EXIF data to pick my next lens Converting and developing RAW photos on Linux automatically Thank you, 2016 iPhone Don't Make It Work Self-hosted Surveillance with ZoneMinder Backups, Monitoring, and Security for small Mastodon servers Block web scanners with ipset & iptables Executing commands over SSH with GitHub Actions Debian Sid on encrypted ZFS Protect your dangerously insecure redis server Debian: the luxurious boring lifestyle Monitor radiation with a Raspberry Pi Simple Linux server alerts: Know your performance, errors, security, syslog, and security NUC crashes on debian 11 - How I fixed it Basic Linux server security with fail2ban, ossec, and firewall Windows 11 will create heaps of needless trash Domesticated Kubernetes Networking The Cursed Certificate Our mostly disposable and entirely stupid world Trying out OpenBSD (as a Linux geek) Making VoIP Calls with Antique Rotary Phones Monitoring WAN speed with speedtest-cli and ElasticSearch Monitoring WAN latency with InfluxDB The Zeroshell botnet returns Installing Gentoo on a vintage Thinkpad T60 Malware emails 2: Russian boogaloo TP-Link Device Weirdness ElasticSearch broke all my nice things (a story of cascading failure) A New Botnet is Targeting Network Infrastructure Malware on the Wire: Monitoring Network Traffic with Suricata and ClamAV Cloud Threat Protection with OSSEC and Suricata Malware Emails From Jerks Surviving the Apocalypse with an Offline Wikipedia Server Being Attacked by Bots Linux Router, Firewall and IDS Appliance You Probably Don't Need a VPN Fix an Oversharded Elasticsearch Cluster Automating KVM Virtualization Update all your linux servers as fast as possible Cleanup Systemd Journald Storage Stop Putting Your SSH Keys on Github! Clustering KVM with Ceph Storage Stealing Windows Sessions FreeRadius Active Directory Integration Retrieving WPA2 Keys on Windows Deploy MDT Litetouch on Linux with TFTPD and Syslinux Generating MSI transform files with Orca The Inflatable Dinghy Generating Cisco IOS config files with Python Homebrew SAN Getting Cloudy
Restarting Kubernetes pods using a CronJob
2025-11-22 · via Posts on Noah Bailey

In an absolutely perfect world, we’d never have to restart our server software ever, because it would be flawless. There would be no bugs, memory leaks, state locks, and we’d all get along with each other!

Unfortunately, we live in a much crappier world where our software is imperfect, and we don’t have enough time or resources to fix it properly.

In the olden days, we’d just put a one-liner in root’s crontab, and be done with it:

0 0 * * *     service foobar restart

But thanks to the wonderful complexity of Kubernetes, it takes a bit more finesse. Advanced cluster schedulers make the hard things easy, but they also make the easy things hard!!

Back in my day, it was one line in the crontab!

For better or for worse, we’ve moved past the simple Debian Days.

Here’s how to achieve the same thing that one crontab entry used to do.

  1. Define cluster permissions for a Service Account
  2. Create a ConfigMap to inject the script into the cluster
  3. Use a CronJob resource to execute the daily restart task
  4. Sit back and watch your pods restart…

Assumptions

First of all, let’s get some assumptions clear:

  • The Deployment that must be restarted daily is called foobar
  • The CronJob & ServiceAccount that execute this restart are called foobar-restart
  • The foobar deployment is capable of performing a rolling-restart without any disruption, or disruption at midnight UTC is acceptable
  • Everything can safely be placed in the Default namespace

Cluster permissions

For a cronjob to restart a deployment, it must have a Role and ServiceAccount to have sufficient permissions. By default, a pod cannot alter the kubernetes environment itself, so it must be specifically granted this access. This Role is then associated with the ServiceAccount, which is an identity that the Pod assumes at runtime. This means that the Pod can act a bit like somebody sitting at a PC using the Kubectl tool, but with a much more restricted set of allowed commands.

So in summary, we must create:

  • A ServiceAccount - an identity for our CronJob
  • A Role - The components of our Cluster that the Pod may alter
  • A RoleBinding - An association of the ServiceAccount to the Role
---
kind: ServiceAccount
apiVersion: v1
metadata:
  name: foobar-restart
  namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: foobar-restart
  namespace: default
rules:
  - apiGroups: ["apps", "extensions"]
    resources: ["deployments"]
    resourceNames: ["foobar"]
    verbs: ["get", "patch", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: foobar-restart
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: foobar-restart
subjects:
  - kind: ServiceAccount
    name: foobar-restart
    namespace: default

Next, the restart script may be wrapped in the configmap.

Restart script

To execute the restart, a very simple script is created that uses the kubectl tool to perform a rolling restart of the foobar deployment. This bash script has a pair of very important safety features, lines 2&3, that I would recommend everybody use when possible.

Instead of simply scp‘ing the shell script into the /opt directory of a Debian box somewhere, in the Kubernetes world it’s inserted into a ConfigMap resource. This is essentially a generic wrapper for any text or binary data that must be passed through to a Pod at a given filesystem mount path. Instead of using it to inject a config file, it is being used to place a shell script in our Job Pod.

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: foobar-restart
data:
  restart.sh: |
    #!/bin/bash
    set -euo pipefail
    trap 'echo "Error restarting!"' ERR 
    kubectl rollout restart deploy/foobar
    kubectl rollout status  deploy/foobar    

CronJob template

With the authorization & config pieces ready, we can deploy the CronJob for the restart.

A ConJob on its own simply creates Job resources at a given interval, which themselves are just Pods with different handling for their exit codes. When a typical Pod exits with a return code 0 it is restarted immediately, but with a Job it is marked as Complete.

---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: foobar-restart
  namespace: default
spec:
  concurrencyPolicy: "Forbid"
  schedule: '0 0 * * *' # Midnight UTC
  jobTemplate:
    spec:
      backoffLimit: 5
      activeDeadlineSeconds: 300
      template:
        spec:
          nodeSelector:
            type: "private"
          containers:
          - name: kubectl
            image:  alpine/k8s:1.33.0
            command: [ "/bin/bash", "/scripts/restart.sh" ]
            volumeMounts:
            - name: foobar-restart
              mountPath: /scripts
          restartPolicy: Never
          serviceAccountName: foobar-restart
          volumes:
          - name: foobar-restart
            configMap:
              defaultMode: 0644
              name: foobar-restart

If using a service mesh like Isito, make sure to include an additional annotation to exclude the sidecar for this pod, or else the job will be “in progress” forever since the sidecar process won’t ever exit.

spec:
  jobTemplate:
    spec: 
      template:
        metadata:
          annotations:
            sidecar.istio.io/inject: "false"

During execution

When the CronJob triggers at midnight, it will output a log more or less like this:

deployment.apps/foobar restarted
Waiting for deployment spec update to be observed...
Waiting for deployment "foobar" rollout to finish: 0 out of 1 new replicas have been updated...
Waiting for deployment "foobar" rollout to finish: 0 out of 1 new replicas have been updated...
Waiting for deployment "foobar" rollout to finish: 0 of 1 updated replicas are available...
Waiting for deployment "foobar" rollout to finish: 0 of 1 updated replicas are available...
deployment "foobar" successfully rolled out

When complete, you’ll have a fresh new pod in place of the old one. And with this in place, you can simply ignore the leaky memory situation that caused this in the first place! Hurrah!