Skip to content
LATEST

🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.

Upgradix
Upgradix Code. Learn. Ship.

Immutable Machine & Container Images with Packer

In traditional server management, engineers log into live servers via SSH, install runtimes, tweak firewall rules, and patch packages by hand. Over time, every server becomes slightly different. When a production outage hits at 2 AM, nobody knows what was changed on that machine six months ago.

Immutable infrastructure solves this problem completely. Instead of modifying running servers, you bake runtimes (such as .NET or Node.js), OS security hardening, and monitoring agents into a single, versioned image using HashiCorp Packer. Whenever you need an update, you build a new image and replace the old servers.

What you will learn
  • Why immutable images beat manual server configuration and eliminate configuration drift.
  • How HashiCorp Packer builds reproducible machine and container images from code.
  • How to bake Node.js or .NET runtimes, OS hardening, and monitoring agents into an image.
  • How to write a complete app.pkr.hcl template with a shell provisioner smoke test.
  • How to run packer init and packer build in a hands-on lab.
  • Common pitfalls, best practices, and real-world DevOps interview questions.

1. What Is Immutable Infrastructure?

The word “immutable” means something cannot be changed after it is created. In cloud and DevOps engineering, immutable infrastructure means you never SSH into a running server to install a patch or upgrade Node.js or .NET.

Instead, you treat servers like disposable appliances. If you need to update a security setting or upgrade a runtime, you update your Packer template, build version v1.0.2 of the image, test it, and deploy fresh instances from that image while retiring v1.0.1.

Aspect Mutable Servers (Traditional) Immutable Images (Packer)
Updates SSH into live servers and run update scripts Build a new versioned image and replace instances
Configuration drift High – servers slowly become unique “snowflakes” Zero – every instance boots from the exact same image
Rollback speed Slow and risky – hard to undo partial changes Instant – redeploy the previous known-good image version
Boot & scaling time Slow – new servers must download and install packages at boot Fast – runtimes and agents are already pre-baked
Audit & compliance Difficult to prove what is installed on each host Full traceability through Git-versioned HCL templates

2. Why Bake Runtimes, Hardening & Agents Ahead of Time?

When an auto-scaling group launches a new server during a traffic spike, you do not want it spending five minutes running apt-get install or downloading the .NET runtime from the internet. If a package repository goes down during scaling, your new servers fail to start.

By baking everything into a golden image with Packer, you gain three major advantages:

  • Pre-installed Runtimes: Whether your team runs Node.js 22 LTS or .NET 8/9 Runtime, baking it into the image guarantees every environment (Dev, QA, Staging, Production) executes on the exact same binary version.
  • Built-in OS Hardening: Disable root SSH logins, remove unnecessary packages, configure firewall defaults, and apply CIS security benchmarks once during the image build rather than hoping every server gets hardened later.
  • Ready-to-Run Monitoring Agents: Pre-install observability tools like the CloudWatch Agent, Prometheus Node Exporter, or OpenTelemetry Collector so every new machine reports metrics and logs the second it boots.

3. How Packer Builds an Immutable Image

Packer uses a simple, automated pipeline. It reads your HCL (HashiCorp Configuration Language) template, spins up a temporary build environment, runs your installation and smoke-test scripts, saves the final image artifact, and destroys the temporary environment.

Packer Immutable Image Build Pipeline

1. HCL Template app.pkr.hcl 2. Builder Launch Temp VM / Container 3. Bake & Harden Runtime + OS + Agent 4. Smoke Test Verify binaries Pass 5. Versioned Image Saved app-runtime:1.0.0 / AWS AMI Auto Cleanup Destroy temp instance If the smoke test fails, Packer aborts immediately and never publishes a broken image.

Packer automates the entire lifecycle: launch a clean base, install and harden everything, verify with a smoke test, save the versioned artifact, and tear down the temporary build host.

4. Core Building Blocks of a Packer HCL Template

Modern Packer uses HCL2 files ending in .pkr.hcl. Every template is organized into four clean blocks:

HCL Block Purpose Common Example
packer {} Declares required plugins and Packer version hashicorp/docker or hashicorp/amazon
source {} Defines the base image and target platform (Builder) Ubuntu 24.04 container or AWS EC2 AMI
build {} Connects sources to provisioners and post-processors Runs shell scripts, Ansible, and smoke tests
post-processor {} Tags, compresses, or pushes the finished image docker-tag to tag upgradix/node-app:1.0.0

5. Hands-On Lab: Build a Reproducible Image with Packer

In this lab, you will write a Packer HCL template named app.pkr.hcl that builds a reproducible Ubuntu-based container image with Node.js 22 LTS pre-installed, applies basic OS hardening, installs a lightweight monitoring utility, and runs a shell provisioner smoke test. Using the Docker builder lets you run this entire lab locally for free without needing a cloud account.

Prerequisites

  • Packer installed (packer --version should be 1.10+ or newer).
  • Docker Desktop or Docker Engine running locally.

Step 1: Create the Packer Template (app.pkr.hcl)

Create a new folder named packer-immutable-lab and save the following code as app.pkr.hcl.

Example 1: app.pkr.hcl (Node.js Runtime + Hardening + Smoke Test)

packer {
  required_version = ">= 1.10.0"

  required_plugins {
    docker = {
      version = ">= 1.0.8"
      source  = "github.com/hashicorp/docker"
    }
  }
}

variable "image_version" {
  type    = string
  default = "1.0.0"
}

source "docker" "ubuntu_node" {
  image  = "ubuntu:24.04"
  commit = true
  changes = [
    "USER appuser",
    "WORKDIR /opt/app",
    "ENV NODE_ENV=production"
  ]
}

build {
  name = "immutable-node-app"
  sources = [
    "source.docker.ubuntu_node"
  ]

  # 1. Bake Runtime, OS Hardening & Monitoring Agent
  provisioner "shell" {
    inline = [
      "set -euo pipefail",
      "export DEBIAN_FRONTEND=noninteractive",
      "apt-get update",
      "apt-get install -y --no-install-recommends curl ca-certificates gnupg sysstat",

      "# Install Node.js 22 LTS",
      "curl -fsSL https://deb.nodesource.com/setup_22.x | bash -",
      "apt-get install -y --no-install-recommends nodejs",

      "# OS Hardening: Create non-root app user and lock down directory",
      "useradd --create-home --shell /usr/sbin/nologin appuser",
      "mkdir -p /opt/app && chown -R appuser:appuser /opt/app",

      "# Clean apt cache to keep the image small and secure",
      "apt-get clean && rm -rf /var/lib/apt/lists/*"
    ]
  }

  # 2. Shell Provisioner Smoke Test
  provisioner "shell" {
    inline = [
      "set -euo pipefail",
      "echo '--- Running Smoke Tests ---'",
      "node -v",
      "npm -v",
      "id appuser",
      "test -d /opt/app",
      "which mpstat",
      "node -e \"console.log('SMOKE TEST OK: Node runtime verified')\""
    ]
  }

  # 3. Tag the final versioned image
  post-processor "docker-tag" {
    repository = "upgradix/node-runtime"
    tags       = [var.image_version, "latest"]
  }
}
Why set -euo pipefail? This shell flag forces the script to stop immediately if any command fails. If the smoke test fails, Packer aborts the build and refuses to tag or publish a broken image.

Step 2: Initialize Packer Plugins

Run packer init . inside your project folder. This downloads the official Docker plugin declared in your required_plugins block.

Example 2: Executing packer init

packer init .

Expected output

Installed plugin github.com/hashicorp/docker v1.0.10 in "~/.config/packer/plugins/github.com/hashicorp/docker/packer-plugin-docker_v1.0.10_x5.0_linux_amd64"

Step 3: Validate and Build the Image

Always validate syntax before building, then execute packer build to bake the image.

Example 3: Executing packer validate and packer build

packer validate app.pkr.hcl
packer build app.pkr.hcl

Expected output

immutable-node-app.docker.ubuntu_node: output will be in this color.

==> immutable-node-app.docker.ubuntu_node: Creating a temporary directory for sharing data...
==> immutable-node-app.docker.ubuntu_node: Pulling Docker image: ubuntu:24.04
==> immutable-node-app.docker.ubuntu_node: Starting docker container...
==> immutable-node-app.docker.ubuntu_node: Provisioning with shell script: /tmp/packer-shell12345
    immutable-node-app.docker.ubuntu_node: Setting up nodejs (22.x)...
==> immutable-node-app.docker.ubuntu_node: Provisioning with shell script: /tmp/packer-shell67890
    immutable-node-app.docker.ubuntu_node: --- Running Smoke Tests ---
    immutable-node-app.docker.ubuntu_node: v22.11.0
    immutable-node-app.docker.ubuntu_node: 10.9.0
    immutable-node-app.docker.ubuntu_node: uid=1001(appuser) gid=1001(appuser) groups=1001(appuser)
    immutable-node-app.docker.ubuntu_node: /usr/bin/mpstat
    immutable-node-app.docker.ubuntu_node: SMOKE TEST OK: Node runtime verified
==> immutable-node-app.docker.ubuntu_node: Committing the container
    immutable-node-app.docker.ubuntu_node: Image ID: sha256:9f84c2a1b7e0...
==> immutable-node-app.docker.ubuntu_node: Killing the container: 4b9a812c7d10
==> immutable-node-app.docker.ubuntu_node: Running post-processor:  (type docker-tag)
    immutable-node-app.docker.ubuntu_node (docker-tag): Tagging image: sha256:9f84c2a1b7e0...
    immutable-node-app.docker.ubuntu_node (docker-tag): Repository: upgradix/node-runtime:1.0.0
    immutable-node-app.docker.ubuntu_node (docker-tag): Repository: upgradix/node-runtime:latest
Build 'immutable-node-app.docker.ubuntu_node' finished after 42 seconds.

==> Builds finished. The artifacts of successful builds are:
--> immutable-node-app.docker.ubuntu_node: Imported Docker image: upgradix/node-runtime:1.0.0

Step 4: Verify Your Baked Image

Run a quick container from your newly baked image to confirm it boots as the non-root appuser with Node.js ready immediately.

Example 4: Testing the baked image

docker run --rm upgradix/node-runtime:1.0.0 sh -c "whoami && node -v"

Expected output

appuser
v22.11.0

6. Baking the .NET Runtime Instead of Node.js

If your services run on ASP.NET Core, you follow the exact same Packer pattern. You simply swap the installation commands in the shell provisioner to install aspnetcore-runtime-8.0 (or 9.0) and update the smoke test to verify dotnet --list-runtimes.

Example 5: Shell provisioner for ASP.NET Core Runtime

  provisioner "shell" {
    inline = [
      "set -euo pipefail",
      "export DEBIAN_FRONTEND=noninteractive",
      "apt-get update",
      "apt-get install -y --no-install-recommends aspnetcore-runtime-8.0",
      "apt-get clean && rm -rf /var/lib/apt/lists/*",
      "dotnet --list-runtimes | grep -q 'Microsoft.AspNetCore.App 8.'"
    ]
  }

To target cloud virtual machines such as AWS EC2 instead of Docker, replace the source "docker" block with source "amazon-ebs". Your provisioner and smoke-test scripts stay almost identical.

7. Step-by-Step Execution Breakdown

Step 1: packer init . reads the required_plugins block and downloads the Docker builder plugin.
Step 2: packer build pulls the clean ubuntu:24.04 base image and starts a temporary container.
Step 3: The first shell provisioner updates packages, installs Node.js 22 LTS and sysstat monitoring tools, creates a restricted appuser, and clears apt caches.
Step 4: The second shell provisioner runs the smoke test to verify the runtime, user account, folder, and monitoring binary.
Step 5: Packer commits the container filesystem into a new immutable image, applies the USER and WORKDIR metadata, destroys the temporary container, and tags the image as upgradix/node-runtime:1.0.0.

8. Common Mistakes and Best Practices

Watch out for secrets inside images: Never bake database passwords, API keys, or private SSH keys into a Packer image. Anyone with access to your image registry or AMI can extract them. Always inject secrets at runtime using environment variables or a secrets manager.
  • Pin your base image and runtime versions: Avoid floating tags like ubuntu:latest in production templates. Pinning ubuntu:24.04 ensures your build today produces the same result next month.
  • Always clean up temporary files: Remove /var/lib/apt/lists/*, installers, and build caches before Packer commits the image. Smaller images boot faster and have a smaller attack surface.
  • Version every image with semantic tags or Git SHAs: Pass versions via packer build -var "image_version=1.0.1" app.pkr.hcl in your CI/CD pipeline so rollbacks are effortless.

9. Hands-On Practice

Beginner Exercise 1: Override the image version at build time

Run packer build and pass a custom version variable (1.1.0) from the command line without editing app.pkr.hcl.

Hint: Use the -var flag: packer build -var "image_version=1.1.0" app.pkr.hcl.

Intermediate Exercise 2: Force a smoke test failure

Add a check for a non-existent binary (such as which fake-agent) inside the smoke test provisioner and run packer build.

Expected result: Packer stops with a non-zero exit code, cleans up the temporary container, and does not create a broken image.

Advanced Exercise 3: Multi-runtime template

Refactor app.pkr.hcl so it uses an external script file (scripts/harden.sh) via the script attribute instead of inline commands, and add a second source block for the .NET 8 runtime.

Hint: Replace inline = [...] with script = "scripts/harden.sh" inside the shell provisioner.

10. Packer & Immutable Images – Interview Questions

Q1. What is configuration drift, and how does Packer prevent it?

Answer: Configuration drift happens when live servers are patched or modified manually over time, causing environments to diverge. Packer prevents drift by baking the OS, runtimes, and security settings into versioned, read-only images that are replaced rather than edited in place.

Q2. What is the difference between Packer and Terraform?

Answer: Packer builds machine and container images (the “what” inside the server, such as runtimes and OS hardening). Terraform provisions and manages the cloud infrastructure (the “where”, such as VPCs, load balancers, and EC2 instances launched from Packer images).

Q3. Why should you include a smoke test provisioner inside a Packer build?

Answer: A smoke test validates that critical runtimes, non-root users, and monitoring agents are installed and working before the image is saved. If a test fails, Packer aborts the build automatically so broken images never reach staging or production.

Q4. Can Packer build images for multiple cloud providers from one template?

Answer: Yes. You can define multiple source blocks (for example, AWS amazon-ebs, Azure azure-arm, and docker) and reference all of them inside a single build block so Packer builds them in parallel using the same provisioners.

Q5. Why shouldn’t you bake application secrets into a Packer image?

Answer: Baked secrets are permanently stored in the image layers or AMI snapshots, making them difficult to rotate and easy to leak. Secrets should always be injected dynamically at container or instance startup via a secrets manager.

11. Conclusion

Moving from manual server setup to immutable images with Packer is one of the highest-impact upgrades a software team can make. By baking your Node.js or .NET runtimes, OS hardening, and monitoring agents into versioned artifacts, you eliminate configuration drift, speed up auto-scaling, and make rollbacks completely predictable.

Start small with the local Docker lab above. Once you are comfortable with packer init, packer validate, and packer build, connect your HCL templates to your CI/CD pipeline so every commit produces a tested, production-ready golden image.

Official Documentation

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Discussion & Comments

0
Guest mode · Login / Register
Post directly as a guest or log in first.

No comments yet

Start the discussion above — ask a question, share a tip, or reply to a comment.

This article is protected. Printing and saving as PDF are disabled.