Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx proxy_pass to a linked docker container

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?

like image 215
Tim-Erwin Avatar asked Jan 19 '15 16:01

Tim-Erwin


2 Answers

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.

like image 197
Bruce Stringer Avatar answered Sep 30 '22 09:09

Bruce Stringer


I believe, Nginx is using its own DNS resolver implementation,

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;     } } 

There is plenty of Docker image with such hack in the entrypoint:

https://github.com/jetbrains-infra/docker-nginx-resolver

entrypoint.sh:

... echo resolver $(awk 'BEGIN{ORS=" "} $1=="nameserver" {print $2}' /etc/resolv.conf) ";" > /etc/nginx/includes/resolver.conf ... 

nginx.conf:

http {     include       /etc/nginx/includes/resolver.conf; .... 
like image 45
Thomas Decaux Avatar answered Sep 30 '22 08:09

Thomas Decaux