Developing Python Applications with Containerization
Best practices for writing Python code that runs efficiently in containerized environments using tools like Docker.
0 likes
9 views
Rule Content
--- description: Enforce best practices for developing Python applications in containerized environments globs: ["**/*.py", "Dockerfile"] tags: [python, docker, containerization, best-practices] priority: 1 version: 1.0.0 --- # Developing Python Applications with Containerization ## Context - Applicable when writing Python code intended to run in Docker containers. - Ensures code is optimized for performance, security, and maintainability within containerized environments. ## Requirements - **Use Official Python Base Images**: Start Dockerfiles with official Python base images to ensure security and compatibility. ```dockerfile FROM python:3.9-slim ``` - **Pin Python Version**: Specify the exact Python version in the Dockerfile to maintain consistency across environments. ```dockerfile FROM python:3.9.7-slim ``` - **Implement Multi-Stage Builds**: Utilize multi-stage builds to create leaner, more secure Docker images. ```dockerfile # Builder stage FROM python:3.9-slim as builder WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Final stage FROM python:3.9-slim WORKDIR /app COPY --from=builder /app /app CMD ["python", "app.py"] ``` - **Avoid Running as Root**: Configure the container to run as a non-root user to enhance security. ```dockerfile RUN adduser --disabled-password --gecos '' appuser USER appuser ``` - **Use .dockerignore File**: Create a `.dockerignore` file to exclude unnecessary files from the Docker image, reducing its size and build time. ```plaintext __pycache__/ *.pyc .git .env ``` - **Optimize Layer Caching**: Order Dockerfile instructions to maximize layer caching and speed up builds. ```dockerfile # Install dependencies before copying application code COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . ``` - **Set Resource Limits**: Define CPU and memory limits to prevent resource exhaustion. ```dockerfile # Example: Set memory limit to 512MB CMD ["python", "app.py"] # In deployment configuration # docker run --memory=512m myapp ``` - **Implement Health Checks**: Use Docker's HEALTHCHECK instruction to monitor the application's health. ```dockerfile HEALTHCHECK CMD curl --fail http://localhost:8000/health || exit 1 ``` - **Log to stdout and stderr**: Configure the application to log directly to stdout and stderr for better integration with container logging systems. ```python import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) ``` - **Use Environment Variables for Configuration**: Manage application configurations through environment variables to enhance flexibility and security. ```python import os db_host = os.getenv('DB_HOST', 'localhost') ``` ## Examples <example> **Valid Dockerfile Example** # Builder stage FROM python:3.9.7-slim as builder WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Final stage FROM python:3.9.7-slim WORKDIR /app COPY --from=builder /app /app RUN adduser --disabled-password --gecos '' appuser USER appuser COPY . . CMD ["python", "app.py"] HEALTHCHECK CMD curl --fail http://localhost:8000/health || exit 1 </example> <example type="invalid"> **Invalid Dockerfile Example** FROM python:latest WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD ["python", "app.py"] *Issues:* - Uses `latest` tag, leading to potential inconsistencies. - Installs dependencies after copying all files, reducing layer caching efficiency. - Runs as the root user, posing security risks. - Lacks health checks and resource limits. </example>