Learn Docker Help

Docker Images: Blueprint do Seu Container 🎨

╔═══════════════════════════════════════════════════════════╗ β•‘ IMAGE ARCHITECTURE MATRIX β•‘ β•‘ β•‘ β•‘ Base Image Layer [Alpine/Ubuntu/Debian] β•‘ β•‘ ↓ β•‘ β•‘ Dependencies Layer [Runtime/Libraries] β•‘ β•‘ ↓ β•‘ β•‘ Application Layer [Your Code/Apps] β•‘ β•‘ ↓ β•‘ β•‘ Configuration Layer [ENV/Settings] β•‘ β•‘ ↓ β•‘ β•‘ Runtime Layer [CMD/ENTRYPOINT] β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Fundamentos de Imagens πŸ“š

Conceitos Básicos

  • Imagem: Template read-only para containers

  • Container: Instância executável de uma imagem

  • Layer: Camada incremental de mudanças

  • Registry: Repositório de imagens

  • Tag: Identificador de versão

  • Digest: Hash SHA256 único da imagem

Tipos de Imagens

  1. Base Images

    • Scratch

    • Alpine (5MB)

    • Debian Slim (80MB)

    • Ubuntu (120MB)

  2. Runtime Images

    • node:alpine

    • python:slim

    • openjdk:slim

  3. Application Images

    • nginx:alpine

    • postgres:alpine

    • redis:alpine

Anatomia Detalhada πŸ”¬

Sistema de Camadas

# AnΓ‘lise de camadas docker history --no-trunc nginx:latest # Metadata detalhada docker inspect --format='{{.RootFS.Layers}}' nginx:latest # Exportar imagem docker save nginx:latest | tar -tvf -

Estrutura Interna

# Exemplo de construΓ§Γ£o em camadas FROM alpine:3.14 # Layer 1: Base OS RUN apk add --no-cache python3 # Layer 2: Runtime COPY ./app /app # Layer 3: Application ENV APP_ENV=production # Layer 4: Configuration CMD ["python3", "/app/main.py"] # Layer 5: Runtime command

Gerenciamento Avançado πŸ› οΈ

Image Operations

# Criar tag local docker tag source:latest target:v1.0 # Salvar imagem como tar docker save myapp:latest > myapp.tar # Carregar imagem de tar docker load < myapp.tar # Filtrar imagens docker images --filter "dangling=true" docker images --filter "label=environment=prod"

Batch Operations

# Remover todas imagens nΓ£o utilizadas docker image prune --all --force # Remover por padrΓ£o docker images -q "python*" | xargs docker rmi # Limpar imagens antigas docker images --format "{{.ID}}\t{{.CreatedAt}}" | sort -k 2 | head -n 5 | cut -f1 | xargs docker rmi

Sistema de Tags 🏷️

Convenções de Versionamento

# Tags especΓ­ficas registry.example.com/app:1.0.0 username/app:latest custom/app:dev-build # Multi-arquitetura docker pull --platform linux/amd64 nginx docker pull --platform linux/arm64 nginx

Boas Práticas πŸ“

DO's βœ…

  • Use tags específicas

  • Minimize camadas

  • Otimize cache

  • Documente dependências

  • Implemente multi-stage builds

DON'Ts ❌

  • Evite latest em produção

  • Não armazene secrets

  • Não instale pacotes desnecessários

  • Não ignore .dockerignore

  • Não use imagens não oficiais sem verificação

Image Operations Matrix πŸ“Š

Operação

Comando

Uso Comum

Build

docker build

Criar nova imagem

Pull

docker pull

Baixar do registry

Push

docker push

Enviar para registry

Tag

docker tag

Criar alias/versão

Remove

docker rmi

Deletar imagem

Inspect

docker inspect

Ver metadata

Prune

docker image prune

Limpar não usadas

Otimização de Imagens πŸš€

Redução de Tamanho

# Multi-stage build FROM node:alpine AS builder WORKDIR /app COPY . . RUN npm ci && npm run build FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html

Cache Optimization

# Ordem eficiente COPY package*.json ./ RUN npm install COPY . . RUN npm run build

Registry Management 🌐

Docker Hub

# Login docker login [options] [SERVER] # Logout docker logout [SERVER] # Pull de registry privado docker pull private-registry.com/app:tag

Advanced Security πŸ”’

Image Signing

# Configurar DCT (Docker Content Trust) export DOCKER_CONTENT_TRUST=1 # Gerar chaves docker trust key generate mykey # Assinar imagem docker trust sign myregistry/myimage:tag # Verificar assinatura docker trust inspect --pretty myregistry/myimage:tag

Security Scanning

# Trivy scan trivy image python:3.9-alpine # Snyk scan snyk container test nginx:latest # Anchore scan anchore-cli image add nginx:latest anchore-cli image wait nginx:latest anchore-cli image vuln nginx:latest os

Monitoring & Metrics πŸ“Š

Image Analytics

# Tamanho das camadas docker history --no-trunc --format "{{.Size}}\t{{.CreatedBy}}" nginx:latest # Uso de disco docker system df -v --format "{{.Type}}\t{{.TotalCount}}\t{{.Size}}" # Cache status docker builder prune -f --filter until=24h

Performance Tracking

# Build time analysis time docker build --no-cache . # Layer size tracking docker image inspect myapp:latest -f '{{.RootFS.Layers}}' # Pull time metrics time docker pull large-image:latest

Advanced Troubleshooting πŸ”§

Debug Techniques

# Debug build DOCKER_BUILDKIT=1 docker build --progress=plain . # Layer inspection docker save myimage:latest | tar -xC /tmp/image-layers # Network issues docker pull --verbose registry.example.com/image:tag

Common Issues Matrix

Problema

Diagnóstico

Solução

Pull Timeout

docker pull -v

Verificar rede/proxy

Build Failure

--no-cache

Limpar cache/deps

Layer Issues

docker history

Otimizar Dockerfile

Space Issues

docker system df

Prune/cleanup

Automation & CI/CD πŸ€–

GitHub Actions

name: Docker Build on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up QEMU uses: docker/setup-qemu-action@v1 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 - name: Login to DockerHub uses: docker/login-action@v1 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Build and push uses: docker/build-push-action@v2 with: context: . platforms: linux/amd64,linux/arm64 push: true tags: user/app:latest

Automated Testing

# Test script #!/bin/bash set -e # Build image docker build -t test-image . # Run container tests docker run --rm test-image npm test # Security scan trivy image test-image # Cleanup docker rmi test-image

Waifu Advanced Tips πŸ’«

Quick Reference Pro πŸ“‹

╔════════════════════════════════════════════════════╗ β•‘ ADVANCED IMAGE MANAGEMENT β•‘ ╠════════════════════════════════════════════════════╣ β•‘ Multi-arch β”‚ docker buildx build --platform all β•‘ β•‘ Sign β”‚ docker trust sign image:tag β•‘ β•‘ Scan β”‚ trivy image nginx:latest β•‘ β•‘ Analyze β”‚ docker history --no-trunc image β•‘ β•‘ Debug β”‚ DOCKER_BUILDKIT=1 docker build . β•‘ β•‘ Optimize β”‚ docker build --squash . β•‘ β•‘ Monitor β”‚ docker events --filter type=image β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Advanced Checkpoint βœ…

Você agora domina:

  • [x] Arquitetura interna de imagens

  • [x] Multi-stage builds avançados

  • [x] Registry privado e autenticação

  • [x] Signing e scanning

  • [x] Debug e troubleshooting

  • [x] CI/CD integration

  • [x] Performance optimization

Next Level Steps 🎯

  1. Container Orchestration

  2. Advanced Security

  3. Custom Base Images

  4. Registry Federation

  5. Image Policy Management

16 abril 2025