Nginx Reverse Proxy – How to Setup

dockernginxreverse-proxyubuntu-14.04

I am trying to get hostnames for my docker containers, and since I can only use a reverse proxy for that, I am trying to achieve exactly that with the help of nginx.

One docker container is a webservice that exposes the port 8080 to the my localhost.

So I can access the webserver via:

http://localhost:8080

Instead I rather want to use:

http://webservice.local

Hence I added to my /etc/hosts

127.0.0.1 webservice.local

I then installed nginx and added to the /etc/nginx/sites-available/default:

server {
     listen 80 default_server;
     listen [::]:80 default_server ipv6only=on;

     root /usr/share/nginx/html;
     index index.html index.htm;

     # Make site accessible from http://localhost/
     server_name localhost;

     location / {
             # First attempt to serve request as file, then
             # as directory, then fall back to displaying a 404.
             try_files $uri $uri/ =404;
             # Uncomment to enable naxsi on this location
             # include /etc/nginx/naxsi.rules
     }


     location webservice.local {
         proxy_pass http://localhost:8080
     }

After reloading nginx I get the following the error ERR_CONNECTION_REFUSED when trying to open up http://webservice.local in my browser.

What did I do wrong? How can I setup the reverse proxy properly?

Best Answer

I'm not sure this is the correct syntax. Try something like that:

upstream myupstream {
    server 127.0.0.1:8080 fail_timeout=2s;
    keepalive 32;
}

location / {
     proxy_pass http://myupstream;
     proxy_redirect http://myupstream/ /;
}

something along these lines..

But if you just want to redirect port 8080 to 80 why not use a network utility like socat?

Then you should add virtualhosts in nginx for each upstream, and add those virtualhosts in DNS or /etc/hosts, which will all resolve to localhost.

Or you can just avoid the upstream and use virtualhosts like so:

server {
  listen 80;
  server_name myvirtualhost1.local;
  location / {
    proxy_pass http://127.0.0.1:8080;
}

server {
  listen 80;
  server_name myvirtualhost2.local;
  location / {
    proxy_pass http://127.0.0.1:9090;
}