Docker是一个开源的容器化平台,允许开发者将应用及其依赖打包到轻量级、可移植的容器中,确保应用在不同环境中一致运行。
Kubernetes是一个开源的容器编排系统,用于自动化容器化应用的部署、扩展和管理。它提供了服务发现、负载均衡、自动扩展、滚动更新等高级功能。
[Docker容器] → [Pod] → [Deployment/ReplicaSet] → [Service] → [Ingress]
安装Docker:
# 在Linux上安装Docker
curl -fsSL https://get.docker.com | sh
sudo systemctl enable --now docker
安装Kubernetes工具:
# 安装kubectl
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
# 安装minikube(用于本地开发)
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube
创建Dockerfile:
FROM nginx:alpine
COPY . /usr/share/nginx/html
EXPOSE 80
构建镜像:
docker build -t my-app:v1 .
测试镜像:
docker run -p 8080:80 my-app:v1
# 登录Docker Hub
docker login
# 标记镜像
docker tag my-app:v1 username/my-app:v1
# 推送镜像
docker push username/my-app:v1
创建部署文件 deployment.yaml
:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: username/my-app:v1
ports:
- containerPort: 80
创建服务文件 service.yaml
:
apiVersion: v1
kind: Service
metadata:
name: my-app-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
应用配置:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 80
使用ConfigMap和Secret:
apiVersion: v1
kind: ConfigMap
metadata:
name: my-app-config
data:
app.properties: |
color=blue
log.level=info
然后在Deployment中引用:
envFrom:
- configMapRef:
name: my-app-config
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-app-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
在Deployment中挂载:
volumeMounts:
- name: storage
mountPath: /data
volumes:
- name: storage
persistentVolumeClaim:
claimName: my-app-pvc
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: my-app-monitor
spec:
selector:
matchLabels:
app: my-app
endpoints:
- port: web
interval: 30s
使用Fluentd或Filebeat作为sidecar容器收集日志。
镜像优化:
安全实践:
CI/CD集成:
问题1:Pod处于Pending状态
- 检查资源配额:kubectl describe pod <pod-name>
- 检查节点资源:kubectl describe nodes
问题2:镜像拉取失败 - 检查镜像名称和标签 - 确保有正确的镜像拉取密钥
问题3:服务无法访问 - 检查服务类型和端口映射 - 检查网络策略
通过以上步骤,您可以成功地将Docker容器与Kubernetes集成,实现高效的容器编排和管理。