背景介绍
api服务开发完毕之后如何快速部署实现负载均衡。如果不是重量级的项目,非常建议使用 Docker Swarm来实现,非常简单高效且稳定。
关于Docker Swarm集群的构建详见我的另一篇博客:Docker Swarm集群搭建
相关文件准备(这里以一个ocr服务为例)
- docker-compose.yml
version: '3.8'
services:
nginx:
image: nginx:1.21
ports:
- "8080:8088"
configs:
- source: nginx.conf
target: /etc/nginx/nginx.conf
networks:
- ocr
deploy:
replicas: 1
restart_policy:
condition: on-failure
placement:
constraints:
- node.labels.ocr.replica==1
api-server:
image: paddleocr:gpu-v3
hostname: api-server
networks:
- ocr
deploy:
replicas: 10
restart_policy:
condition: on-failure
placement:
constraints:
- node.labels.ocr.replica==1
configs:
nginx.conf:
file: ./nginx.conf
networks:
ocr:
external: true # 用已经创建好的网络
- nginx.conf
user nginx;
worker_processes 2;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
upstream ocr_servers {
server api-server:8866; # Docker 会自动进行 DNS 负载均衡到 API 服务的各个实例
}
server {
listen 8088;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://ocr_servers;
proxy_read_timeout 600; # 可根据实际需求调整
proxy_redirect off;
proxy_buffering off;
}
}
}
创建专用网络:
docker network create --driver overlay ocr
部署
docker stack deploy -c docker-compose.yml ocr
查看
docker stack ls
NAME SERVICES
ocr 2
docker service ls
ID NAME MODE REPLICAS IMAGE PORTS
c94y6w6r8lok ocr_api-server replicated 10/10 paddleocr:gpu-v3
iliarkza8v68 ocr_nginx replicated 1/1 nginx:1.21 *:8080->8088/tcp
标签:log,service,Swarm,server,nginx,api,proxy,ocr
From: https://www.cnblogs.com/JentZhang/p/18027763