大网数据广告活动
服务器运维问答

nginx refresh upstream server IP

· 52CE 我爱测

I have a Docker setup with one Django container and one nginx serving static files. I have nginx configured in the standard way: upstream main_web { server web:8000; } server { location / { proxy_pass http://main_web; #... } } I …

问题原文

原帖链接 · user1496984 · CC BY-SA 3.0

I have a Docker setup with one Django container and one nginx serving static files. I have nginx configured in the standard way:

upstream main_web {
    server web:8000;
}
server {
    location / {
        proxy_pass http://main_web;
        #...
    }

}

I use the /etc/hosts entry to get the IP address of the Django container.

When I restart the Django container, its IP address is updated, which reflects to the hosts file. But nginx keeps giving a 502 Bad Gateway error. Things work fine when I manually restart nginx.

Isn't there a way to tell nginx to resolve the IP again if it's not reachable?

社区高分解答

原帖链接 · lloiacono · CC BY-SA 4.0

When you use a variable to specify the domain name in the proxy_pass directive, NGINX re‑resolves the domain name when its TTL expires. You must include the resolver directive to explicitly specify the name server (NGINX does not refer to /etc/resolv.conf). More here

Using Docker, you can check your current dns resolver and add that to your nginx configuration. Check /etc/resolv.conf.

For example using docker-compose you can set the name of the service in your nginx vhost configuration. Asume we have this setup:

docker-compose.yml

version: "3"
services:
  my-backend-service: # we will use this name in our nginx vhost conf
    image: some-image
  lb:
    image: nginx
    volumes:
      - ".docker/etc/nginx/default.conf:/etc/nginx/conf.d/default.conf"
    ports:
      - 80:80

A few things about the above configuration, note that I do not add a container-name to the backend service, so I can scale it freely. Also pay attention to the service name, we will use that in Nginx vhost conf so it resolves to the instances ip via DNS. Finally, Nginx is listening on port 80 and the backend-services are listening on 8080 (as an example, could be anything)

default.conf

resolver 127.0.0.11 valid=10s; # 127.0.0.1 comes from /etc/resolv.conf on the nginx container

server {
    location / {
        set $backend_servers my-backend-service;
        proxy_pass http://$backend_servers:8080;
    }
}

To test this:

  • docker-compose up -d
  • docker-compose scale my-backend-service=5
  • docker-compose logs -f my-backend-service

Now you can start making requests to localhost and Nginx is going to use the DNS resolver you specify to get the ip addresses of the backend services, and will re-resolve the domain name when the TTL expires.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-09-15)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。