Docker Community Forums

Share and learn in the Docker community.

Forward real ip from Nginx docker to Apache docker

Hi,

I have a Nginx container running as reverse proxy for some other docker containers. One of them has an apache server running and logs login attempts in web_php.log.

Right now I am getting the real ip-address in the nginx log and the docker gateway in my apache logs. Is it possible to forward the real ip to apache?

Nginx is running in network mode = host and my other containers running in bridged mode.

Thanks in advance!

Appart from running in docker, your question is not realy docker related. The same would happen if nginx would run on a bare metal machine and apache would be on the same or a different machine.

Typicaly people set the http headers X-Forwarded-For, X-Real-IP, X-Forwarded-Host, X-Forwarded-Proto in their reverse proxy. It is up to the target application to make use of those headers. Applications designed to work with reverse proxies usual do so.

Let’s build reverse proxy image:

$ docker build -t reverseproxy .
Sending build context to Docker daemon 4.608 kB
Step 1/2 : FROM nginx:alpine
alpine: Pulling from library/nginx
627beaf3eaaf: Pull complete
d7d23baed7e7: Pull complete
7ded693c7a29: Pull complete
6856facfdc93: Pull complete
Digest: sha256:ebd2b85803e78100a582385f7eac56cd367561f0f2bab005f784cda95818d41f
Status: Downloaded newer image for nginx:alpine
—> 5a35015d93e9
Step 2/2 : COPY nginx.conf /etc/nginx/nginx.conf
—> 3e31efad8bda
Removing intermediate container edd9450463ad
Successfully built 3e31efad8bda

We can check the create image:

$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
reverseproxy latest 3e31efad8bda About a minute ago 15.5 MB

Note that we copied the following nginx.conf to our reverse proxy container:

nginx.conf:

worker_processes 1;

events { worker_connections 1024; }

http {

sendfile on;

upstream docker-nginx {
    server nginx:80;
}

upstream docker-apache {
    server apache:80;
}

server {
    listen 8080;

    location / {
        proxy_pass         http://docker-nginx;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }
}

server {
    listen 8081;

    location / {
        proxy_pass         http://docker-apache;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }
}

}