Nginx - Getting proxy_pass to work

I’m having a problem trying to get Nginx to proxy a path to another server that is also running in Docker.

To illustrate, I’m using Nexus server as an example.

This is my first attempt…

docker-compose.yml:-

version: '2'
services:
  nexus:
    image: "sonatype/nexus3"
    ports:
     - "8081:8081"
    volumes:
     - ./nexus:/nexus-data

  nginx:
    image: "nginx"
    ports:
    - "80:80"
    volumes:
    - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro

nginx.conf:-

worker_processes 4;
events { worker_connections 1024; }
http {
        server {
              listen 80;
     
              location /nexus/ {
                proxy_pass http://localhost:8081/;
              }
        }
}

When I hit http://localhost/nexus/, I get 502 Bad Gateway with the following log:-

nginx_1  | 2017/05/29 02:20:50 [error] 7#7: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /nexus/ HTTP/1.1", upstream: "http://[::1]:8081/", host: "localhost"
nginx_1  | 2017/05/29 02:20:50 [error] 7#7: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /nexus/ HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "localhost"
nginx_1  | 172.18.0.1 - - [29/May/2017:02:20:50 +0000] "GET /nexus/ HTTP/1.1" 502 575 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"

In my second attempt…,

docker-compose.yml - I added links to Nginx configuration:-

version: '2'
services:
  nexus:
    image: "sonatype/nexus3"
    ports:
     - "8081:8081"
    volumes:
     - ./nexus:/nexus-data

  nginx:
    image: "nginx"
    ports:
    - "80:80"
    volumes:
    - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
	links:
	- nexus:nexus

nginx.conf… Instead of using http://localhost:8081/, I use http://nexus:8081/:-

worker_processes 4;
events { worker_connections 1024; }
http {
        server {
              listen 80;
     
              location /nexus/ {
                proxy_pass http://nexus:8081/;
              }
        }
}	

Now, when I hit http://localhost/nexus/, it gets proxied properly but the web content is partially rendered. When inspecting the HTML source code of that page, the javascript, stylesheet and image links are pointing to http://nexus:8081/[path]… hence, 404.

What should I change to get this to work properly?

Thank you very much.

you could use links in docker-compose.yml like this:

links:
- nexus

and in nginx.conf : proxy_pass http://nexus:8081.

because link will create new line in /etc/hosts, to make nexus point to real ip address of nexus container.