Nginx 缓存 DNS 查找并忽略我的解析器设置

Y T*_*sky 7 dns nginx docker

我正在使用码头群。我在 API 前面放置了一个 nginx 容器以进行缓存。由于每次部署 API 时,它都会创建一个新的内部 IP,因此我根据 swarm 文档使用我的服务tasks.api 的名称。下面是我的位置块

proxy_cache_path /var/cache/nginx/ta_api levels=1:2 keys_zone=api_cache:10m max_size=10g
                  inactive=60m use_temp_path=off;

server {
    listen       80;
    server_name  localhost;

    location / {
      proxy_pass http://tasks.api:10010;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_buffering on;
      proxy_cache api_cache;
      proxy_cache_bypass $http_upgrade;
      # Add header to see if response was cached
      add_header X-Cache-Status $upstream_cache_status;

      # Allow one cache-update request at a time sent to an origin server.
      proxy_cache_lock on;
      # Permit revalidation of stale cached responses.
      proxy_cache_revalidate on;

      # proxy_cache_valid 200 1d;
      # Delivering Cached Content When the Origin is Down
      proxy_cache_use_stale error timeout invalid_header updating
                            http_500 http_502 http_503 http_504;

      # Do all updates in background. With proxy_cache_use_stale, allows stale
      # cached responses to be served.
      proxy_cache_background_update on;
    }
}
Run Code Online (Sandbox Code Playgroud)

我还添加resolver 127.0.0.11 ipv6=off valid=15s;到我的 http 块中。但是,当我重新部署 API 并获得新的 API 时,nginx 仍会尝试发送到旧 IP。

当我在 nginx 容器上安装绑定工具时,我正在运行 nginx 容器标签,nginx:1.15.12-alpine我可以看到我正在使用获取新 IPdig tasks.api

我不知道下一步该尝试什么。我可以对私有 IP 进行硬编码,但这不是 docker 方式......

Jam*_*sJJ 11

NGINX 只会在启动时进行 DNS 查找,并永久缓存固定主机名。要在运行时启用 DNS 查找,您需要将固定主机名更改为动态变量。因此,在OP情况下,将原始proxy_pass行更改为:

set $target_host tasks.api ;
proxy_pass http://$target_host:10010;
Run Code Online (Sandbox Code Playgroud)

  • NGINX 博客文章详细介绍了此处的所有选项 - https://www.nginx.com/blog/dns-service-discovery-nginx-plus/ (2认同)