docker run --name my-nginx -d -p 80:80 nginx
FROM nginx:latest
# 复制自定义配置文件
COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d/ /etc/nginx/conf.d/
# 复制静态文件
COPY static/ /usr/share/nginx/html/
# 暴露端口
EXPOSE 80 443
CMD ["nginx", "-g", "daemon off;"]
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
nginx.conf: |
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
docker run --name my-nginx \
-v /path/to/nginx.conf:/etc/nginx/nginx.conf \
-v /path/to/logs:/var/log/nginx \
-d nginx
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
template:
spec:
volumes:
- name: nginx-config
configMap:
name: nginx-config
- name: nginx-logs
emptyDir: {}
docker swarm init
docker service create --name nginx --replicas 3 -p 80:80 nginx
docker service scale nginx=5
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
kubectl autoscale deployment nginx-deployment --cpu-percent=50 --min=3 --max=10
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-canary
spec:
replicas: 1
template:
spec:
containers:
- name: nginx-new
image: nginx:new-version
# 部署新版本
kubectl apply -f nginx-blue.yaml
# 切换流量
kubectl patch svc nginx-service -p '{"spec":{"selector":{"version":"blue"}}}'
worker_processes auto;
worker_rlimit_nofile 100000;
events {
worker_connections 4000;
use epoll;
multi_accept on;
}
resources:
limits:
cpu: "2"
memory: "1Gi"
requests:
cpu: "500m"
memory: "512Mi"
scrape_configs:
- job_name: 'nginx'
static_configs:
- targets: ['nginx-service:9113']
FROM nginx/nginx-prometheus-exporter:latest
CMD ["-nginx.scrape-uri", "http://nginx/status"]
FROM nginx:latest
USER nginx
securityContext:
readOnlyRootFilesystem: true
server {
listen 443 ssl http2;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
}
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
# Docker容器日志
docker logs my-nginx
# Kubernetes Pod日志
kubectl logs nginx-pod-1234
# 查看容器资源使用
docker stats my-nginx
# Kubernetes资源监控
kubectl top pod nginx-pod-1234
# 测试服务可达性
kubectl run -i --tty --rm debug --image=busybox --restart=Never -- sh
wget -O- nginx-service:80
# 检查DNS解析
nslookup nginx-service
通过以上指南,您可以实现Nginx的高效容器化部署和集群管理,确保服务的高可用性、可扩展性和安全性。根据实际业务需求,可以进一步调整配置参数和部署策略。