» Python: Building Event-Driven Microservices with Kafka » 5. Deployment » 5.1 Dockerfile

Dockerfile

Docker allows developers to package their applications along with all dependencies into a single unit called a container. This ensures consistency across different environments, such as development, testing, and production, reducing the "it works on my machine" problem.

Install Docker: https://docs.docker.com/engine/install/

Dockerfile for the web service

Add service/web/Dockerfile:

# Use Alpine Linux with Python 3 as base image
FROM python:3.12.3-alpine3.19

RUN apk add --no-cache gcc libc-dev librdkafka-dev

# Set the working directory in the container
WORKDIR /app

# Copy the dependencies file to the working directory
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the current directory contents into the container at /app
COPY service/ /app/service

CMD ["uvicorn", "service.web.main:app", "--host", "0.0.0.0", "--port", "8000"]

Add service/web/.dockerignore:

# Ignore Python cache directories
**/__pycache__

config.yml

Alpine Linux is a lightweight and secure Linux distribution that is particularly well-suited for containerized environments, embedded systems, and resource-constrained environments where efficiency and security are paramount.

Build the docker image for the web service:

docker build -t lrbooks_web_py:latest -f service/web/Dockerfile .

Similarly, add 2 more Dockerfiles:

Dockerfile for the trend service

Add service/trend/Dockerfile:

# Use Alpine Linux with Python 3 as base image
FROM python:3.12.3-alpine3.19

RUN apk add --no-cache gcc libc-dev librdkafka-dev

# Set the working directory in the container
WORKDIR /app

# Copy the dependencies file to the working directory
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the current directory contents into the container at /app
COPY service/ /app/service

CMD ["uvicorn", "service.trend.main:app", "--host", "0.0.0.0", "--port", "8001"]

Add service/trend/.dockerignore:

# Ignore Python cache directories
**/__pycache__

config.yml

Dockerfile for the recommendation service

Add service/recommendation/Dockerfile:

# Use Alpine Linux with Python 3 as base image
FROM python:3.12.3-alpine3.19

RUN apk add --no-cache gcc libc-dev librdkafka-dev

# Set the working directory in the container
WORKDIR /app

# Copy the dependencies file to the working directory
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the current directory contents into the container at /app
COPY service/ /app/service

CMD ["uvicorn", "service.recommendation.main:app", "--host", "0.0.0.0", "--port", "8002"]

Add service/recommendation/.dockerignore:

# Ignore Python cache directories
**/__pycache__

config.yml

With all the Dockerfiles, we‘re well prepared to run them all together in the Docker Compose.

PrevNext