How to Mock Docker Image Non-Root User in Python

This Python class simulates Docker image layers and inspects whether the final user is a non-root user, returning UID, GID, and security status.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 11 views 0 copies

Python code

42 lines
Python 3.9+
from pathlib import Path


class DockerImageMock:
    def __init__(self, name, tag):
        self.name = name
        self.tag = tag
        self.layers = []
        self.user = "root"

    def add_file(self, path, content):
        self.layers.append({"file": path, "content": content})

    def set_user(self, username, uid, gid, home):
        self.user = username
        self.layers.append({
            "user": {
                "name": username,
                "uid": uid,
                "gid": gid,
                "home": home
            }
        })

    def inspect(self):
        last_user_layer = self.layers[-1] if self.layers and "user" in self.layers[-1] else None
        return {
            "image": f"{self.name}:{self.tag}",
            "layers_count": len(self.layers),
            "runs_as_uid": last_user_layer["user"]["uid"] if last_user_layer else 0,
            "runs_as_gid": last_user_layer["user"]["gid"] if last_user_layer else 0,
            "home_dir": last_user_layer["user"]["home"] if last_user_layer else "/root",
            "is_secure": self.user != "root" and bool(last_user_layer)
        }


if __name__ == "__main__":
    image = DockerImageMock("python-app", "v1.0")
    image.add_file("/app/app.py", "print('hello')")
    image.set_user("appuser", 1001, 1001, "/home/appuser")

    print(image.inspect())

Output

stdout
{'image': 'python-app:v1.0', 'layers_count': 2, 'runs_as_uid': 1001, 'runs_as_gid': 1001, 'home_dir': '/home/appuser', 'is_secure': True}

How it works

The DockerImageMock class tracks file and user layers added to an image. set_user appends a layer that overrides the default root user. The inspect method checks the last layer; if it's a user change, it returns the corresponding UID, GID, and home directory. The is_secure flag is True only when the final user is not root and a user layer exists. This mimics the Dockerfile pattern of using USER to switch to a non-root user for security.

Common mistakes

  • Forgetting that the last user layer determines the running user, not the first one.
  • Assuming `is_secure` is True if any user layer exists, even if root is set later.
  • Not handling the case where no user layer is added, leading to root by default.

Variations

  1. Use a dataclass to represent the image instead of a plain class.
  2. Implement the mock with a list of instructions, like a real Dockerfile parser.

Real-world use cases

  • Validating that generated Dockerfiles set a non-root user before deployment.
  • Writing unit tests for Docker image building scripts that enforce security policies.
  • Simulating image inspection in CI pipelines to catch root-user configurations early.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.