Container & Kubernetes Security
Securing containers and Kubernetes is a critical part of a modern DevOps workflow.
Best Practices for Writing Secure Dockerfiles
- Use a Minimal Base Image: Start with a small, trusted base image (e.g.,
alpineordistroless) to reduce the attack surface. - Run as a Non-Root User: Create a dedicated user and group in your Dockerfile and use the
USERinstruction to switch to that user. - Don't Leak Sensitive Information: Use multi-stage builds to avoid leaving build tools, development dependencies, or secrets in the final image.
- Scan for Vulnerabilities: Use tools like
trivyorsnykto scan your images for known vulnerabilities.
Scanning Container Images for Vulnerabilities
You can integrate container scanning into your CI/CD pipeline to catch vulnerabilities before they reach production.
- Using
trivy:# Scan an image
trivy image my-app:latest
# Fail the build if vulnerabilities are found
trivy image --exit-code 1 --severity HIGH,CRITICAL my-app:latest
Using Kubernetes Network Policies
Network Policies are a Kubernetes resource that control the traffic between Pods. By default, all Pods in a cluster can communicate with each other. You can use Network Policies to restrict traffic to only what is necessary.
- Example Network Policy:
This policy denies all ingress traffic to Pods with the label
app=db, except from Pods with the labelapp=api.apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-allow-api
spec:
podSelector:
matchLabels:
app: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: api
Secrets Management Best Practices in Kubernetes
- Use Kubernetes Secrets: Store sensitive information, such as passwords and API keys, in Kubernetes Secrets rather than in ConfigMaps or environment variables.
- Enable Encryption at Rest: Configure your Kubernetes cluster to encrypt Secrets at rest.
- Use a Secrets Management Tool: For more advanced use cases, consider using a dedicated secrets management tool like HashiCorp Vault or AWS Secrets Manager. These tools provide features like dynamic secrets, automatic rotation, and fine-grained access control.