saint

kubernetes

A Tale of Kubernetes Image Caching and What We Learned

TL;DR: Rebuilt a Docker image with the same tag. Kubernetes cached the old broken image. Pods crashed for 51 minutes. The fix? One line: imagePullPolicy: Always. Here's the full story.


The Setup

It was a Sunday morning. We were upgrading BookWyrm (a federated social reading platform) from v0.8.1 to v0.8.2 on our Kubernetes cluster. The plan was simple:

  1. Update the version tag
  2. Trigger the GitHub Actions workflow
  3. Wait for the build
  4. Deploy
  5. Celebrate

What could go wrong?


Everything Goes Wrong

9:20 AM: The Deployment

I triggered the workflow. GitHub Actions spun up, built the Docker image, pushed it to the registry, and deployed to Kubernetes.

βœ“ Build complete
βœ“ Image pushed: release-0.8.2
βœ“ Deployment applied

Looking good! I watched the pods start rolling out.

9:24 AM: The Crash

NAME                   READY   STATUS
web-86f4676f8b-zwgfs   0/1     CrashLoopBackOff

Every. Single. Pod. Crashed.

I pulled the logs:

ModuleNotFoundError: No module named 'bookwyrm'

The entire BookWyrm application was missing from the container.

The Investigation

I dove into the Dockerfile. We had accidentally used the upstream bookwyrm/Dockerfile instead of our custom one. That Dockerfile only copied requirements.txt – not the actual application code.

# The broken Dockerfile
FROM python:3.10
COPY requirements.txt .
RUN pip install -r requirements.txt
# ... but WHERE'S THE CODE? 😱

Classic. Easy fix!


The First β€œFix” (That Wasn't)

10:37 AM: The Quick Fix

I created a fix commit that switched to the correct Dockerfile:

# The correct Dockerfile
FROM python:3.10
RUN git clone https://github.com/bookwyrm-social/bookwyrm .
RUN git checkout v0.8.2
RUN pip install -r requirements.txt
# Now we have the code!

I committed the changes... and forgot to push to GitHub.

Then I triggered the workflow again.

Naturally, GitHub Actions built from the old code (because I hadn't pushed). The broken image was rebuilt and redeployed.

Pods still crashing. Facepalm moment #1.

10:55 AM: Actually Pushed This Time

I realized my mistake, pushed the commits, and triggered the workflow again.

This time the build actually used the fixed Dockerfile. I watched it clone BookWyrm, install dependencies, everything. The build logs looked perfect:

#9 [ 5/10] RUN git clone https://github.com/bookwyrm-social/bookwyrm .
#9 0.153 Cloning into '.'...
#9 DONE 5.1s

Success! The image was built correctly and pushed.

I watched the pods roll out... and they crashed again.

ModuleNotFoundError: No module named 'bookwyrm'

The exact same error.

This made no sense. The image was built correctly. I verified the build logs. The code was definitely in the image. What was happening?


The Real Problem

I checked what image the pods were actually running:

kubectl get pod web-c98d458c4-x5p6z -o jsonpath='{.status.containerStatuses[0].imageID}'
ghcr.io/nycterent/ziurkes/bookwyrm@sha256:934ea0399adad...

Then I checked what digest we just pushed:

release-0.8.2: digest: sha256:0a2242691956c24c687cc05d...

Different digests. The pods were running the OLD image!

The Kubernetes Image Cache Trap

Here's what I didn't know (but definitely know now):

When you specify an image in Kubernetes without :latest:

image: myregistry.com/app:v1.0.0

Kubernetes defaults to imagePullPolicy: IfNotPresent. This means:

  • If the image tag exists locally on the node β†’ use cached version
  • If the image tag doesn't exist β†’ pull from registry

We rebuilt the image with the same tag (release-0.8.2). The node already had an image with that tag (the broken one). So Kubernetes said β€œgreat, I already have release-0.8.2” and used the cached broken image.

Even when I ran kubectl rollout restart, it created new pods... which immediately used the same cached image.

Why This Happens

This behavior makes sense for immutable tags. If release-0.8.2 is supposed to be immutable, there's no reason to re-pull it every time.

But we had mutated the tag by rebuilding it with the same name.

But Wait – What's the REAL Root Cause?

At this point, you might think β€œAh, the root cause is image caching!”

Not quite.

The image caching is what broke. But the root cause is why could this happen in the first place?

Root cause analysis isn't about what failedβ€”it's about what we can change to prevent it from happening again.

The actual root causes:

  1. No deployment validation – Nothing checked if our image contained application code
  2. No image management policy – We had no rules about tag reuse or imagePullPolicy
  3. No process guardrails – Our workflow let us deploy untested changes to production
  4. No automated testing – No smoke tests, no staging environment, no safety net

The wrong Dockerfile and the image caching were symptoms. The root cause was missing processes that would have caught these mistakes.


The Solution

The fix ended up being multi-part:

1. Migrate to Harbor Registry

We consolidated all images into our Harbor registry instead of split between GitHub Container Registry and Harbor. This gave us better control over image management.

2. Add imagePullPolicy: Always

The critical fix in every deployment:

spec:
  containers:
    - name: web
      image: uostas/ziurkes/bookwyrm:release-0.8.2
      imagePullPolicy: Always  # ← This one line

With imagePullPolicy: Always, Kubernetes pulls the image every time, regardless of what's cached.

3. Update imagePullSecrets

Since we moved to Harbor, we needed to update the registry credentials:

imagePullSecrets:
  - name: uostas-registry  # Harbor credentials

We deployed these changes and... πŸŽ‰

NAME                     READY   STATUS    RESTARTS   AGE
web-5cd76dfd5b-qv4ln     1/1     Running   0          51s
celery-worker-...        1/1     Running   0          73s
celery-beat-...          1/1     Running   0          74s
flower-...               1/1     Running   0          65s

All pods healthy! Service restored!


Lessons Learned

1. Build Process Validation (Prevention > Detection)

The Real Lesson: We had no validation that our images contained working code.

What we should have had:

# In Dockerfile - fail build if app code missing
RUN test -f /app/bookwyrm/__init__.py || \
    (echo "ERROR: BookWyrm code not found!" && exit 1)
# In deployment - fail pod startup if app broken
livenessProbe:
  exec:
    command: ["python", "-c", "import bookwyrm"]

If we'd had these, the broken image would never have reached production.

2. Image Management Policy (Not Just Best Practices)

The Real Lesson: β€œBest practices” aren't enough – you need enforced policies.

What we implemented:

  • βœ… Required: imagePullPolicy: Always in all deployments
  • βœ… Required: Images must go to Harbor registry (not ghcr.io)
  • βœ… Recommended: Include git SHA in tags: release-0.8.2-a1b2c3d
  • βœ… Alternative: Pin to digest: image@sha256:abc123...

These aren't suggestions – they're now requirements in our deployment YAMLs.

3. Deployment Guardrails (Make Mistakes Impossible)

The Real Lesson: Manual processes need automated checks.

What we added:

# Pre-deployment checks (automated)
- Commits pushed to remote? βœ…
- CI build passed? βœ…
- Image exists at expected digest? βœ…
- Staging environment healthy? βœ…

Can't deploy to production without passing all checks.

4. The β€œFive Whys” Actually Works

The incident: – Pods crashed β†’ Why? Missing code – Missing code β†’ Why? Wrong Dockerfile – Wrong Dockerfile β†’ Why? Unclear which to use – Unclear β†’ Why? Inadequate documentation – Inadequate docs β†’ Why? No review process for critical changes

The root cause wasn't β€œwrong Dockerfile” – it was no process to prevent deploying wrong Dockerfiles.

5. Root Cause vs. Proximate Cause

Proximate causes (what broke): – Used wrong Dockerfile – Reused image tag – Forgot to push commits

Root causes (what we can change): – No validation of build artifacts – No image management policy – No deployment guardrails

Fix the proximate causes: You solve this incident. Fix the root causes: You prevent the whole class of incidents.


The Cost

Downtime: 51 minutes (9:24 – 10:15 AM) Total investigation time: ~70 minutes Number of failed deployment attempts: 3 Lesson learned: Priceless

But seriously – this was a production outage for a social platform people rely on. 51 minutes of β€œsorry, we're down” is not acceptable.


Prevention Checklist

Here's what we now do before every deployment:

Pre-Deployment

  • [ ] Changes committed and pushed to remote
  • [ ] CI build passed successfully
  • [ ] Image tag is unique (includes git SHA or build number)
  • [ ] Or: imagePullPolicy: Always is set
  • [ ] Smoke tests verify app code exists in image

During Deployment

  • [ ] Watch pod status (kubectl get pods -w)
  • [ ] Check logs immediately if crashes occur
  • [ ] Verify image digest matches what was built

Post-Deployment

  • [ ] All pods healthy
  • [ ] Health endpoints responding
  • [ ] Run database migrations if needed
  • [ ] Check error tracking (Sentry) for issues

The Technical Details

For those who want to reproduce this behavior (in a safe environment!):

# Build image v1
docker build -t myapp:v1.0.0 .
docker push myregistry.com/myapp:v1.0.0

# Deploy to Kubernetes
kubectl apply -f deployment.yaml
# Pods start with image from registry

# Now rebuild THE SAME TAG with different code
docker build -t myapp:v1.0.0 .  # Different code!
docker push myregistry.com/myapp:v1.0.0

# Try to redeploy
kubectl rollout restart deployment/myapp

# Pods will use CACHED image (old v1.0.0), not new one
# Because imagePullPolicy defaults to IfNotPresent

Fix it:

spec:
  template:
    spec:
      containers:
        - name: myapp
          image: myregistry.com/myapp:v1.0.0
          imagePullPolicy: Always  # Now it works!

Resources


Conclusion

A single line – imagePullPolicy: Always – would have prevented 51 minutes of downtime.

The silver lining? We learned this lesson in a relatively low-stakes environment, documented it thoroughly, and now have processes to prevent it from happening again.

And hopefully, by sharing this story, we've saved someone else from the same headache.

The next time you rebuild a Docker image with the same tag, remember this story. And add that one line.


Have you encountered similar Kubernetes caching issues? How did you solve them? Drop a comment on Mastodon.


Update: Migration Complete βœ…

After all pods came up healthy, we still needed to run database migrations for BookWyrm v0.8.2. Migration 0220 took about 10 minutes to complete (it was a large data migration). Once finished, the service was fully operational.

Final timeline: 70 minutes from first crash to fully operational service.


Tags: #kubernetes #docker #devops #incident-response #lessons-learned #image-caching #imagepullpolicy #bookwyrm #harbor-registry #troubleshooting


This post is based on a real production incident on 2025-11-16. Names and some details have been preserved because documenting failures helps everyone learn.

Comment in the Fediverse @saint@river.group.lt

Published: November 13, 2025 Author: River Instance Team Reading Time: 8 minutes


The Mission

Today we upgraded our Mastodon instance (river.group.lt) from version 4.5.0 to 4.5.1. While this might sound like a routine patch update, we used it as an opportunity to make our infrastructure more secure and our deployment process more automated. Here's what we learned along the way.


Why Upgrade?

When glitch-soc (our preferred Mastodon variant) released version 4.5.1, we reviewed the changelog and found 10 bug fixes, including:

  • Better keyboard navigation in the Alt text modal
  • Fixed issues with quote posts appearing as β€œunquotable”
  • Improved filter application in detailed views
  • Build fixes for ARM64 architecture

More importantly: no database migrations, no breaking changes, and no new features that could introduce instability. This is what we call a β€œsafe upgrade” – the perfect candidate for improving our processes while updating.


The Starting Point

Our Mastodon setup isn't quite standard. We run:

  • glitch-soc variant (Mastodon fork with extra features)
  • Custom Docker images with Sentry monitoring baked in
  • Kubernetes deployment via Helm charts
  • AMD64 architecture (important for cross-platform builds)

This means we can't just pull the latest official image – we need to rebuild our custom images with each new version.


The Problem We Solved

Before this upgrade, our build process looked like this:

# Find Harbor registry credentials (where?)
# Copy-paste username and password
docker login registry.example.com
# Enter credentials manually
# Update version in 4 different files
# Hope they all match
./build.sh
# Wait for builds to complete
# Manually verify everything worked

The issues: – Credentials stored in shell history (security risk) – Manual steps prone to typos – No automation = easy to forget steps – Credentials sitting in ~/.docker/config.json unencrypted

We knew we could do better.


The Solution: Infisical Integration

Infisical is a secrets management platform – think of it as a secure vault for credentials that your applications can access automatically. Instead of storing Harbor registry credentials on our laptop, we:

  1. Stored credentials in Infisical (one-time setup)
  2. Updated our build script to fetch credentials automatically
  3. Automated the Docker login process

Now our build script looks like this:

#!/bin/bash
set -e

VERSION="v4.5.1"
REGISTRY="registry.example.com/library"
PROJECT_ID="<your-infisical-project-id>"

echo "πŸ”‘ Logging in to Harbor registry..."
# Fetch credentials from Infisical
HARBOR_USERNAME=$(infisical secrets get \
  --domain https://secrets.example.com/api \
  --projectId ${PROJECT_ID} \
  --env prod HARBOR_USERNAME \
  --silent -o json | jq -r '.[0].secretValue')

HARBOR_PASSWORD=$(infisical secrets get \
  --domain https://secrets.example.com/api \
  --projectId ${PROJECT_ID} \
  --env prod HARBOR_PASSWORD \
  --silent -o json | jq -r '.[0].secretValue')

# Automatic login
echo "${HARBOR_PASSWORD}" | docker login ${REGISTRY} \
  --username "${HARBOR_USERNAME}" --password-stdin

# Build and push images...

Note: Code examples use placeholder values. Replace registry.example.com, secrets.example.com, and <your-infisical-project-id> with your actual infrastructure endpoints.

The benefits: – βœ… No credentials in shell history – βœ… No manual copy-pasting – βœ… Audit trail of when credentials were accessed – βœ… Easy credential rotation – βœ… Works the same on any machine with Infisical access


The Upgrade Process

With our improved automation in place, the actual upgrade was straightforward:

Step 1: Research

We used AI assistance to research the glitch-soc v4.5.1 release: – Confirmed it was a patch release (low risk) – Verified no database migrations required – Reviewed all 10 bug fixes – Checked for breaking changes (none found)

Lesson: Always research before executing. 15 minutes of reading can prevent hours of rollback.

Step 2: Update Version References

We needed to update the version in exactly 4 places:

  1. docker-assets/build.sh – Build script version variable
  2. docker-assets/Dockerfile.mastodon-sentry – Base image version
  3. docker-assets/Dockerfile.streaming-sentry – Streaming image version
  4. values-river.yaml – Helm values for both image tags

Lesson: Keep a checklist of version locations. It's easy to miss one.

Step 3: Build Custom Images

cd docker-assets
./build.sh

The script now: – Fetches credentials from Infisical βœ“ – Logs into Harbor registry βœ“ – Builds both images with --platform linux/amd64 βœ“ – Pushes to registry βœ“ – Provides clear success/failure messages βœ“

Build time: ~5 seconds (thanks to Docker layer caching!)

Step 4: Deploy to Kubernetes

cd ..
helm upgrade river-mastodon . -n mastodon -f values-river.yaml

Helm performed a rolling update: – Old pods kept running while new ones started – New pods pulled v4.5.1 images – Old pods terminated once new ones were healthy – Zero downtime for our users

Step 5: Verify

kubectl exec -n mastodon deployment/river-mastodon-web -- tootctl version
# Output: 4.5.1+glitch

All three pod types (web, streaming, sidekiq) now running the new version. Success! πŸŽ‰


What We Learned

1. Automation Compounds Over Time

The Infisical integration took about 60 minutes to implement. The actual version bump took 30 minutes. That might seem like overkill for a β€œsimple” upgrade.

But here's the math: – Manual process: 5 minutes per build to manage credentials – Automated process: 0 minutes – Builds per year: ~20 upgrades and tests – Time saved annually: 100 minutes – Payback period: 12 builds (~6 months)

Plus, we eliminated a security risk. The real value isn't just time – it's confidence and safety.

2. Separate Upstream from Custom

We keep the upstream Helm chart (Chart.yaml) completely untouched. Our customizations live in: – Custom Dockerfiles (add Sentry) – Values overrides (values-river.yaml) – Build scripts

Why this matters: We can pull upstream chart updates without conflicts. Our changes are additive, not modifications.

3. Test Incrementally

We didn't just run the full build and hope it worked. We tested:

  1. βœ“ Credential retrieval from Infisical
  2. βœ“ JSON parsing with jq
  3. βœ“ Docker login with retrieved credentials
  4. βœ“ Image builds
  5. βœ“ Image pushes to registry
  6. βœ“ Kubernetes deployment
  7. βœ“ Running version verification

Each step validated before moving forward. When something broke (initial credential permissions), we caught it immediately.

4. Documentation Is for Future You

We wrote a comprehensive retrospective covering: – What went well – What we learned – What we'd do differently next time – Troubleshooting guides for common issues

In 6 months when we upgrade to v4.6.0, we'll thank ourselves for this documentation.

5. Version Numbers Tell a Story

Understanding semantic versioning helps assess risk:

  • v4.5.0 β†’ v4.5.1 = Patch release (bug fixes only, low risk)
  • v4.5.x β†’ v4.6.0 = Minor release (new features, moderate risk)
  • v4.x.x β†’ v5.0.0 = Major release (breaking changes, high risk)

This informed our decision to proceed quickly with minimal testing.


What We'd Do Differently Next Time

Despite the success, we identified improvements:

High Priority

1. Validate credentials before building

Currently, we discover authentication failures during the image push (after building). Better:

# Test login BEFORE building
if ! docker login ...; then
  echo "❌ Auth failed"
  exit 1
fi

2. Initialize Infisical project config

Running infisical init in the project directory creates a .infisical.json file, eliminating the need for --projectId flags in every command.

3. Add version consistency checks

A simple script to verify all 4 files have matching versions before building would catch human errors.

Medium Priority

4. Automated deployment verification

Replace manual kubectl checks with a script that: – Waits for pods to be ready – Extracts running version – Compares to expected version – Reports success/failure

5. Dry-run mode for build script

Test the script logic without actually building or pushing images. Useful for testing changes to the script itself.


The Impact

Before this session: – Manual credential management – 5+ minutes per build for login – Credentials in shell history (security risk) – No audit trail

After this session: – Automated credential retrieval – 0 minutes per build for login – Credentials never exposed (security improvement) – Full audit trail in Infisical – Repeatable process documented

Plus: We're running Mastodon v4.5.1 with 10 bug fixes, making our instance more stable for our users.


Lessons for Other Mastodon Admins

If you run a Mastodon instance, here's what we learned that might help you:

For Small Instances

Even if you're running standard Mastodon without customizations:

  1. Document your upgrade process – Your future self will thank you
  2. Test in staging first – If you don't have staging, test with dry-run/simulation
  3. Always check release notes – 5 minutes of reading prevents hours of debugging
  4. Use semantic versioning to assess risk – Patch releases are usually safe

For Custom Deployments

If you run custom images like we do:

  1. Separate upstream from custom – Keep modifications isolated and additive
  2. Automate credential management – Shell history is not secure storage
  3. Use Docker layer caching – Speeds up builds dramatically
  4. Platform flags matter – --platform linux/amd64 if deploying to different architecture
  5. Verify the running version – Don't assume deployment worked, check it

For Kubernetes Deployments

If you deploy to Kubernetes:

  1. Rolling updates are your friend – Zero downtime is achievable
  2. Helm revisions enable easy rollback – helm rollback is simple and fast
  3. Verify pod image versions – Check what's actually running, not just deployed
  4. Monitor during rollout – Watch pod status, don't just fire and forget

The Numbers

Session Duration: 90 minutes total – Research: 15 minutes – Version updates: 10 minutes – Infisical integration: 60 minutes – Build & deploy: 5 minutes

Deployment Stats: – Downtime: 0 seconds (rolling update) – Pods affected: 3 (web, streaming, sidekiq) – Helm revision: 166 – Rollback complexity: Low (single command)

Lines of code changed: 18 lines across 4 files Lines of documentation written: 629 lines (retrospective) Security improvements: 1 major (credential management)


Final Thoughts

What started as a simple patch upgrade turned into a significant infrastructure improvement. The version bump was almost trivial – the real work was automating away manual steps and eliminating security risks.

This is what good ops work looks like: using routine maintenance as an opportunity to make systems better. The 60 minutes we spent on Infisical integration will pay dividends on every future build. The documentation we wrote will help the next person (or future us) upgrade with confidence.

Mastodon v4.5.1 is running smoothly, our build process is more secure, and we learned lessons that will make the next upgrade even smoother.


Resources

For Mastodon Admins: – Mastodon Upgrade Documentation – glitch-soc Releases

For Infrastructure: – Infisical (Secrets Management) – Docker Build Best Practices – Helm Upgrade Documentation

Our Instance: – river.group.lt – Live Mastodon instance – Running glitch-soc v4.5.1+glitch – Kubernetes + Helm deployment – Custom images with Sentry monitoring


Questions?

If you're running a Mastodon instance and have questions about: – Upgrading glitch-soc variants – Custom Docker image workflows – Kubernetes deployments – Secrets management with Infisical – Zero-downtime upgrades

Feel free to reach out! We're happy to share what we've learned.


Tags: #mastodon #glitch-soc #kubernetes #devops #infrastructure #security #automation


This blog post is part of our infrastructure documentation series. We believe in sharing knowledge to help others running similar systems. All technical details are from our actual upgrade session on November 13, 2025.

Comment in the Fediverse @saint@river.group.lt