docker多个端口怎么分
Docker多个容器不能有相同端口号的处理方案问题背景在docker里用同一份镜像创建4个容器,网络选择bridge模式,A服务在四个容器中都使用了同一个端口号(6000);为了减少对外暴露的端口数,另外使用了nginx对这4个服务实例做代理,4个服务实例分属4个upstream,使用了类似/service1、/service2的路径来访问4个实例。
此时从本地访问任一服务,则会报502错误,百思不得其解。
connect() failed (111: Connection refused) while connecting to upstream
compose文件
version: '2' networks: nn: driver: bridge services: service-1: container_name: service-1 image: foo networks: - nn volumes: - ./logs/1:/apps/aaa/bbb-logs - ./common:/apps/aaa/bbb - ./xxx/1.xml:/ccc/targets.xml entrypoint: foo.sh command: start app=foo port=6000 service-2: container_name: service-2 image: foo networks: - nn volumes: - ./logs/2:/apps/aaa/bbb-logs - ./common:/apps/aaa/bbb - ./xxx/2.xml:/ccc/targets.xml entrypoint: foo.sh command: start app=foo port=6000 service-3: container_name: service-3 image: foo networks: - nn volumes: - ./logs/3:/apps/aaa/bbb-logs - ./common:/apps/aaa/bbb - ./xxx/3.xml:/ccc/targets.xml entrypoint: foo.sh command: start app=foo port=6000 service-4: container_name: service-4 image: foo networks: - nn volumes: - ./logs/4:/apps/aaa/bbb-logs - ./common:/apps/aaa/bbb - ./xxx/4.xml:/ccc/targets.xml entrypoint: foo.sh command: start app=foo port=6000 nginx: container_name: nginx image: nginx:1.15-alpine ports: - 6001:6001 networks: - nn volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./logs/nginx:/var/log/nginx
nginx.conf
worker_processes 8; worker_rlimit_nofile 65535; events { use epoll; worker_connections 65535; } http { include mime.types; default_type aplication/octet-stream; sendfile on; log_format main '[$time_local]$remote_addr-$upstream_addr "$request" $status $body_bytes_sent'; upstream service1.local { server service-1:6000; } upstream service2.local { server service-2:6000; } upstream service3.local { server service-3:6000; } upstream service4.local { server service-4:6000; } server { listen 6001; client_max_body_size 100M; proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; location /service1/ { proxy_pass http://service1.local/; } location /service2/ { proxy_pass http://service2.local/; } location /service3/ { proxy_pass http://service3.local/; } location /service4/ { proxy_pass http://service4.local/; } location /nginx_status { stub_status on; access_log off; } } }
此时curl localhost:6001/service1/api/v1/....就会报上面的502错误,按理说每一个容器都是有各自的网卡,不同容器的端口号应该不冲突才对。
解决方案暂时没有较好的方案,只能对4个服务使用不同的端口号,nginx也相应地修改。
补充:同台服务器部署多套docker容器,端口重定向问题
在生成环境,部署多个容器,访问多个端口;
例如:-p 80:80 -p 81:81
81地址退出的时候,直接访问到80端口的地址。
误区:开始以为是cookie的问题,因为刷新了cookie(cookie是不区分端口号)
最终找到了原因:redirect问题,因为退出重定向到登录页面
解决方案:配置nginx参数proxy_set_header HOST $host; 改成 proxy_set_header HOST $host:81;
因为不管怎样,请求参数投都带上了端口号。
网上还有一种方法:修改proxy_redirect 参数(不过试过没有生效)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持开心学习网。如有错误或未考虑完全的地方,望不吝赐教。