問題背景
在docker里用同一份鏡像創(chuàng)建4個容器,網(wǎng)絡選擇bridge模式,A服務在四個容器中都使用了同一個端口號(6000);為了減少對外暴露的端口數(shù),另外使用了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錯誤,按理說每一個容器都是有各自的網(wǎng)卡,不同容器的端口號應該不沖突才對。
解決方案
暫時沒有較好的方案,只能對4個服務使用不同的端口號,nginx也相應地修改。
補充:同臺服務器部署多套docker容器,端口重定向問題
在生成環(huán)境,部署多個容器,訪問多個端口;
例如:-p 80:80 -p 81:81
81地址退出的時候,直接訪問到80端口的地址。
誤區(qū):開始以為是cookie的問題,因為刷新了cookie(cookie是不區(qū)分端口號)
最終找到了原因:redirect問題,因為退出重定向到登錄頁面
解決方案:配置nginx參數(shù)
proxy_set_header HOST $host; 改成 proxy_set_header HOST $host:81;
因為不管怎樣,請求參數(shù)投都帶上了端口號。
網(wǎng)上還有一種方法:修改proxy_redirect 參數(shù)(不過試過沒有生效)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。