Skip to content

Container_security

This chapter covers container security best practices.


Container Security Layers
+------------------------------------------------------------------+
| |
| 1. Registry Security |
| - Use trusted images |
| - Scan for vulnerabilities |
| - Sign images |
| |
| 2. Image Security |
| - Minimal base images |
| - No secrets in images |
| - Multi-stage builds |
| |
| 3. Runtime Security |
| - Drop capabilities |
| - Run as non-root |
| - Resource limits |
| - Network isolation |
| |
| 4. Orchestration Security |
| - RBAC |
| - Network policies |
| - Pod security policies |
| |
+------------------------------------------------------------------+

# Use specific tags
FROM nginx:1.24
# Don't run as root
USER nginx
# Use read-only filesystem
# docker run --read-only nginx
# Remove unnecessary packages
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

Terminal window
# Don't run privileged
docker run --privileged nginx # AVOID
# Drop capabilities
docker run --cap-drop=all --cap-add=NET_BIND_SERVICE nginx
# User namespace remapping
# /etc/docker/daemon.json
{
"userns-remap": "default"
}
# seccomp profile
docker run --security-opt seccomp=default.json nginx
# AppArmor profile
docker run --security-opt apparmor=docker-default nginx

Terminal window
# Create secret
echo "password" | docker secret create db_password -
# Use in service
docker service create --secret db_password nginx
# Use secret as env var
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password

Terminal window
# Trivy
trivy image nginx:latest
trivy image --severity HIGH,CRITICAL nginx:latest
# Clair
clair-scanner nginx:latest
# Anchore
anchore-cli image add nginx:latest
anchore-cli image vuln nginx:latest

allow-nginx.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-nginx
spec:
podSelector:
matchLabels:
app: nginx
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: client
egress:
- to:
- podSelector:
matchLabels:
app: database

pod.yaml
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
seccompProfile:
type: RuntimeDefault
# Capabilities
securityContext:
capabilities:
drop:
- ALL
add:
- NET_BIND_SERVICE

In this chapter, you learned:

  • ✅ Container security principles
  • ✅ Image security best practices
  • ✅ Runtime security hardening
  • ✅ Secrets management
  • ✅ Image scanning
  • ✅ Network policies
  • ✅ Pod security standards

In this part, you learned:

  • ✅ KVM/QEMU virtualization
  • ✅ Docker fundamentals
  • ✅ Docker advanced networking/storage
  • ✅ Kubernetes basics
  • ✅ Container security

Chapter 61: HA Concepts and Design


Last Updated: February 2026