我将docker-compose
与“Docker for Mac”一起使用,我有两个容器:一个NGINX,一个容器在端口3000上为node-app服务。docker-compose.yml
看起来像这样:
version: "2"
services:
nginx:
build: ./nginx
ports:
- "80:80"
links:
- api
api:
build: ./api
volumes:
- "./api:/opt/app"
在NGINX的配置中,我说:
upstream api {
server api:3000;
}
server {
# ....
location ~ ^/api/?(.*) {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://api;
proxy_redirect off;
}
}
现在,当我在节点代码中更改某些内容并重建容器时
$ docker-compose stop api && docker-compose up -d --build --no-deps api
容器正在重建并启动。问题是,有时容器的内部IP发生了变化,而NGINX对此一无所知。有趣的是,当我进入NGINX容器和
ping api
时,我得到了新的IP地址。$ ping api
PING api (172.19.0.3): 56 data bytes
64 bytes from 172.19.0.3: icmp_seq=0 ttl=64 time=0.236 ms
但是NGINX日志仍然说
2016/10/20 14:20:53 [error] 9#9: *9 connect() failed (113: No route to host) while connecting to upstream, client: 172.19.0.1, server: localhost, request: "GET /api/test HTTP/1.1", upstream: "http://172.19.0.7:3000/api/test", host: "localhost"
上游的
172.19.0.7
仍然是旧IP地址。PS:每次我重建容器时都不会发生这种情况。
最佳答案
这是因为Nginx caches the DNS response for upstream servers-在工作流程中,您只是重新启动应用程序容器,因此Nginx不会重新加载,并且始终将其缓存的IP地址用于api
容器。
如您所见,当您运行一个新的api
容器时,它可以具有不同的IP地址,因此Nginx中的缓存无效。 ping
之所以有效,是因为它不缓存Docker的DNS响应。
假设这仅是针对开发人员的,停机时间不是问题,重建应用程序容器后的docker-compose restart nginx
将重新启动Nginx并清除DNS缓存。
关于nginx - docker 撰写: rebuild of one linked container breaks nginx's upstream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40154585/