Dockerize a model service with a reproducible environment
In this article (5 sections)
A Dockerfile describes how to build an image. It does not prove the image builds, runs, passes a vulnerability scan or serves correct predictions. Keep specification review and executed container evidence separate.
Review the local specification
The deployment lab includes Dockerfile.review and pinned review requirements.
from deployment_cases import docker_case
result = docker_case()
assert result["requirements_all_pinned"] is True
assert result["non_root_user"] is True
assert result["container_build_executed"] is False
print(result["reason"])The file uses a slim Python tag, non-root numeric user and exec-form command. It includes @sha256:REPLACE_WITH_REVIEWED_DIGEST; that is intentionally a placeholder and prevents a reproducible build until an approved real digest replaces it. No container build is claimed.
Build an auditable image
Pin dependencies with hashes where practical and choose a maintained minimal base. Pinning a digest improves reproducibility but also requires a process to review security updates. Copy dependency files before application code to use cache safely. Keep credentials out of layers and build arguments.
Run as non-root, set a read-only filesystem where compatible and restrict network/filesystem permissions. Add health and readiness behavior at the service layer. Generate a software bill of materials and scan the final image; review findings rather than declaring a scan “secure.”
Test inside the container
Build in CI, start the image, send golden valid and invalid requests, verify model hash, check graceful shutdown and measure startup and inference on target architecture. Record the image digest that passed.
The Data Science course distinguishes configuration from executed deployment evidence.
Exercise
Replace the digest placeholder with a reviewed current digest, build and scan the image in an authorized environment, run contract tests and record the resulting image digest and findings.
Continue learning
This article is part of the Model deployment and MLOps sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Create a model rollback runbook.
- Continue with Load-test a prediction API with realistic payloads.
Reference: Docker build best practices.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our Data Science programme — 6 months. From data foundations to machine learning, deep learning and deployment.
Explore Data Science