Advanced Docker Techniques
Container Resource Management
graph TD
A[Resource Management] --> B[CPU Limits]
A --> C[Memory Constraints]
A --> D[Storage Quotas]
Resource Allocation Example
## Limit container to 1 CPU core and 512MB memory
sudo docker run -it --cpus=1 --memory=512m ubuntu /bin/bash
## Set memory and swap limits
sudo docker run -it --memory=1g --memory-swap=2g ubuntu /bin/bash
Docker Compose for Multi-Container Deployment
version: '3'
services:
web:
image: nginx
ports:
- "8080:80"
database:
image: postgres
environment:
POSTGRES_PASSWORD: mysecretpassword
Security Best Practices
Security Technique |
Implementation |
Non-root Containers |
Use USER directive in Dockerfile |
Read-only Filesystem |
Add :ro flag to volume mounts |
Limit Container Capabilities |
Use --cap-drop and --cap-add |
Container Orchestration with Docker Swarm
## Initialize Swarm cluster
sudo docker swarm init
## Create service with replicas
sudo docker service create --replicas 3 --name web nginx
## Scale service dynamically
sudo docker service scale web=5
Advanced Networking Configurations
## Create custom network with subnet
sudo docker network create \
--driver bridge \
--subnet 192.168.0.0/24 \
--gateway 192.168.0.1 \
custom_network
Container Monitoring and Logging
## Real-time container logs
sudo docker logs -f container_name
## Inspect container metrics
sudo docker stats container_name
## Limit log file size
sudo docker run --log-driver json-file \
--log-opt max-size=10m \
--log-opt max-file=3 \
nginx
Dockerfile Optimization Techniques
## Multi-stage build
FROM maven:3.8.1-openjdk-11 AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/app.jar /app.jar
ENTRYPOINT ["java","-jar","/app.jar"]