问题
I have two docker containers with nginx. container1 is linked to container2. Docker then adds an entry to /etc/hosts which I entered into the nginx configuration like so:
server {
location ~ ^/some_url/(.*)$ {
proxy_pass http://container1/$1;
}
}
I can ping container1 from container2, but nginx cannot resolve it:
*1 no resolver defined to resolve container1
How can I proxy_pass a request to another docker container?
回答1:
Use an upstream block instead of the container name directly
upstream backend {
server container1;
}
server {
location ~ ^/some_url/(.*)$ {
proxy_pass http://backend/$1;
}
}
This should allow normal name resolution to occur providing a way to easily use docker links with nginx.
回答2:
You could use embedded Docker DNS service, if enabled, check your container resolver:
cat /etc/resolv.conf
Should be:
nameserver 127.0.0.11
Use this IP as resolver:
server {
location ~ ^/some_url/(.*)$ {
resolver 127.0.0.11;
proxy_pass http://container1/$1;
} }
回答3:
You should take a look at this answer about using /etc/hosts as your resolver: Using /etc/hosts as resolver for url rewriting
Basically, your dns or resolver does not use /etc/hosts to resolve names during a lookup, but you can work around this by installing dnsmasq
and using 127.0.0.1
as your resolver. You can add 127.0.0.1 as the resolver directly in your nginx config:
server {
location ~ ^/some_url/(.*)$ {
resolver 127.0.0.1;
proxy_pass http://container1/$1;
}
}
来源:https://stackoverflow.com/questions/28028789/nginx-proxy-pass-to-a-linked-docker-container