Core Concepts - docker/docker-py

Core Concepts:

  1. Dockerizing Python Applications:

Docker can be used to containerize Python applications. This involves creating a Dockerfile, which contains instructions to build a Python image. The Dockerfile can specify the base image, set up the working directory, copy the application code, install dependencies, and set up the command to run the application. (Source: How to “Dockerize” Your Python Applications | Docker)

Example:

FROM python:3
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD [ "python", "./your-daemon-or-script.py" ]
  1. Docker Compose:

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file, docker-compose.yml, to configure the application services. This file can specify the image to use, environment variables, networking, and other options. (Source: Docker Compose Tutorial: advanced Docker made simple | Educative.io)

Example:

version: '3'
services:
web:
build: .
ports:
- "5000:5000"
  1. Docker-py:

Docker-py is a Python library for the Docker Engine API. It allows Python applications to interact with the Docker Engine, including building, running, and managing containers. (Source: docker-py documentation)

Example:

import docker

client = docker.from_env()
container = client.containers.run('python:3', 'print("Hello, world!")')
output = container.logs()
print(output)
  1. Python-on-whales:

Python-on-whales is a Python library for the Docker CLI. It allows Python applications to interact with the Docker CLI, including building, running, and managing containers. It provides a 1-to-1 mapping between the Docker CLI and the Python library. (Source: Guest Post: Calling the Docker CLI from Python with Python-on-whales | Docker)

Example:

import pythononwhales as powhales

container = powhales.Container.run('python:3', 'print("Hello, world!")')
output = container.logs()
print(output)
  1. Docker Security:

Docker containers have an attack surface that includes the container image, the container runtime, and the host system. It is important to minimize the attack surface by using a minimal base image, limiting the permissions of the container, and keeping the system up to date. (Source: Understanding a Containers Attack Surface | Kube by Example)

Example:

FROM python:3-alpine
RUN apk add --no-cache build-base
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
USER user:user
CMD ["python", "./your-daemon-or-script.py"]

In this example, the base image is python:3-alpine, which is a minimal image based on Alpine Linux. The apk add command installs only the necessary packages, and the USER command sets the user and group to run the container.