Guides

Building Dockerfile best practices and optimization with...

This guide provides a structured approach to building secure, optimized Docker workflows for web applications. Focuses on practical implementation patterns for development, security, and CI/CD integration.

30-45 minutes5 steps
1

Project structure normalization

Create consistent directory layout with .dockerignore, Dockerfile, and build context. Place Dockerfile in root directory and exclude unnecessary files.

.dockerignore
.dockerignore
*.git
node_modules
*.env

Dockerfile
README.md
app/
build/

⚠ Common Pitfalls

  • Including source control files in build context
  • Missing .dockerignore leading to large image sizes
2

Dockerfile optimization

Use multi-stage builds and minimize layers. Combine installation and cleanup steps in single RUN commands.

Dockerfile
FROM golang:1.21 as builder
WORKDIR /app
COPY . .
RUN go mod download && go build -o /myapp

FROM gcr.io/distroless/static-debian12
COPY --from=builder /myapp /myapp
CMD ["/myapp"]

⚠ Common Pitfalls

  • Separating installation and cleanup steps
  • Using apt-get without autoremove
3

Security baseline implementation

Add vulnerability scanning and minimal base images. Verify image integrity with notary.

scan.sh
trivy image myapp:latest
notary -s https://notary.example.com verify myapp:latest

⚠ Common Pitfalls

  • Ignoring high-severity vulnerabilities
  • Not verifying image signatures
4

Docker Compose development setup

Configure services with build contexts, environment variables, and volume mounts for hot reload.

docker-compose.yml
version: '3.8'
services:
  app:
    build: .
    ports:
      - "8080:8080"
    volumes:
      - .:/app
    environment:
      - DEBUG=1

⚠ Common Pitfalls

  • Mounting entire project directory
  • Forgetting to set environment variables
5

CI/CD pipeline integration

Configure build pipelines with cache mounts and image tagging strategies.

.github/workflows/ci.yml
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Build Docker image
      run: |
        docker build --cache-from myapp:latest -t myapp:latest .
        docker tag myapp:latest myregistry.com/myapp:$(git rev-parse --short HEAD)

⚠ Common Pitfalls

  • Not invalidating caches on dependency changes
  • Using insecure registry credentials

What you built

This implementation provides a secure, optimized Docker workflow. Validate each step with your specific application requirements and security policies.