Search Tutorials
--Ads--Containerizing a RAG Application with Docker
Write a Dockerfile and Docker Compose setup for a RAG API with a vector database.
Containers package your RAG service with its exact Python version, libraries and models, so it runs the same on a laptop, a CI server and in production. This lesson writes a production-style Dockerfile for the FastAPI RAG service and a Docker Compose setup that runs it together with a PostgreSQL + pgvector database.
What you will learn
- How to write a small, secure Dockerfile for a Python RAG API
- How to handle embedding models in images (download at build time)
- How to pass secrets and configuration safely
- How to run the API and a vector database together with Docker Compose
Prerequisites
- Docker installed (Docker Desktop on Windows and macOS, Docker Engine on Linux)
- Serving RAG as an API with FastAPI
Project layout
rag-service/
app.py # FastAPI app (from the FastAPI lesson)
retriever.py
rag_helpers.py
requirements.txt
download_models.py # pre-downloads the embedding model
Dockerfile
.dockerignore
compose.yaml
.env # NOT copied into the image
Step 1: Pre-download models at build time
If the embedding model downloads when a container starts, every new container is slow and depends on the internet. Download it during the image build instead:
from sentence_transformers import SentenceTransformer
SentenceTransformer("BAAI/bge-small-en-v1.5") # stored in the Hugging Face cache inside the image
print("models downloaded")
Step 2: The Dockerfile
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
HF_HOME=/opt/hf-cache
WORKDIR /app
# Install dependencies first, so this layer is cached when only code changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Bake the embedding model into the image
COPY download_models.py .
RUN python download_models.py
# Copy the application code
COPY . .
# Run as a non-root user
RUN useradd --create-home appuser && chown -R appuser /app /opt/hf-cache
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
.env
.venv/
__pycache__/
*.pyc
.git/
notebooks/
data/
The .dockerignore file keeps secrets, virtual environments and large data out of the image. Never COPY a .env file or bake API keys into an image: anyone with the image could read them.
Step 3: Build and run
docker build -t rag-service:1.0 .
docker run --rm -p 8000:8000 --env-file .env rag-service:1.0
--env-file passes the API keys at run time. Test it:
curl http://localhost:8000/health
{"status":"ok"}
Step 4: API plus database with Docker Compose
services:
db:
image: pgvector/pgvector:pg17
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: rag
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d rag"]
interval: 5s
retries: 10
api:
build: .
ports:
- "8000:8000"
env_file: .env
environment:
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/rag
depends_on:
db:
condition: service_healthy
volumes:
pgdata:
docker compose up --build
Compose reads POSTGRES_PASSWORD from .env in the same folder. Inside the Compose network, the API reaches the database at the host name db. The named volume pgdata keeps the database between restarts.
Image size and speed tips
- PyTorch is large. If you only need CPU inference, install the CPU build of PyTorch to save gigabytes, or call a hosted embedding API instead of running models in the container.
- Order layers from least to most frequently changed: system packages, dependencies, models, code.
- Multi-stage builds help when you need compilers only at build time.
- Pin versions in
requirements.txtso rebuilds are reproducible.
Common errors and troubleshooting
- The API cannot reach the database: inside Compose use the service name (
db), notlocalhost. - Container restarts on startup: check
docker compose logs api; missing environment variables are the usual cause. - Permission denied writing files: the non-root user needs ownership of folders it writes to.
- Models download on every start: the download step did not run at build time, or
HF_HOMEdiffers between build and run.
Key takeaways
- Install dependencies and download models at build time; copy code last for fast rebuilds.
- Never bake secrets into images; pass them at run time.
- Run as a non-root user with a health check.
- Use Docker Compose to run the API with its vector database locally.
Frequently asked questions
Should the vector database run in Docker in production?
For managed or clustered databases, use the cloud provider's managed service or a Kubernetes operator; Compose is best for development and small deployments.
How do I use a GPU in a container?
Use a CUDA base image and the NVIDIA container toolkit, and request GPUs in your runtime (for example docker run --gpus all).
Practice exercises
- Add a
workerservice to Compose that runs the ingestion script. - Measure the image size, then switch to a CPU-only PyTorch build and compare.
Related tutorials
- Deploying RAG on Kubernetes
- CI/CD for RAG Applications
- RAG with PostgreSQL and pgvector