How to Create Dockerfile for ML Model: Simple Guide
To create a
Dockerfile for an ML model, start with a base image like python, copy your model and code files, install dependencies using pip, and define the command to run your model. This packages your model and environment so it runs consistently anywhere with docker build and docker run.Syntax
A Dockerfile is a text file with instructions to build a Docker image. Key parts include:
- FROM: base image to start from (e.g., python)
- COPY: copy your code and model files into the image
- RUN: run commands like installing packages
- WORKDIR: set working directory inside the container
- CMD: command to run your ML model when container starts
dockerfile
FROM python:3.9-slim WORKDIR /app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . ./ CMD ["python", "app.py"]
Example
This example Dockerfile packages a simple ML model app. It uses Python 3.9, installs dependencies from requirements.txt, copies all files, and runs app.py which loads and serves the model.
dockerfile
FROM python:3.9-slim WORKDIR /app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . ./ CMD ["python", "app.py"]
Output
Successfully built image and container runs your ML model app
Common Pitfalls
Common mistakes when creating Dockerfiles for ML models include:
- Not specifying a lightweight base image, causing large images
- Forgetting to copy all necessary files (model weights, code)
- Not installing dependencies properly, leading to runtime errors
- Using
RUN python app.pyinstead ofCMD, which runs at build time instead of container start
dockerfile
### Wrong way (runs app during build, not container start) FROM python:3.9-slim WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . ./ RUN python app.py ### Right way FROM python:3.9-slim WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . ./ CMD ["python", "app.py"]
Quick Reference
Tips for Dockerfile creation for ML models:
- Use slim or minimal base images to reduce size
- Pin dependency versions in
requirements.txtfor reproducibility - Copy only needed files to keep image clean
- Use
CMDto specify the runtime command - Test your container locally before deployment
Key Takeaways
Start your Dockerfile with a lightweight Python base image like python:3.9-slim.
Copy your ML model files and install dependencies using pip inside the Dockerfile.
Use CMD to specify the command that runs your ML model when the container starts.
Avoid running your app during image build; run it when the container runs.
Keep your Docker image small and reproducible by pinning dependency versions.