Question

How to use nginx as a proxy with Express and docker-compose?

Hi guys, I experience a strange behavior with my Express Server (Node.js) configuration. I have a docker-compose setup with a couple of apps (Rails, Postrges, Express and Express): version: ‘2’

services:
  db:
    image: postgres
    env_file: .env
    volumes:
      - ./postgres-data:/var/lib/postgresql/data
  app:
    image: app-image
    volumes:
      - ./public:/usr/src/app/public
    env_file: .env
    environment:
      RAILS_ENV: production
    depends_on:
      - db
    links:
      - db
    expose:
      - "3000"
  ui:
    image: ui-image
    ports:
      - "4000:4000"
  proxy:
    build:
      context:  ./nginx
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
      - "80:80"
    links:
      - app
      - ui

nginx.conf:

worker_processes 4;
 
events { worker_connections 1024; }
 
http {
	sendfile on;
    
	upstream ui {
		server app:3000;
	}

	upstream ui {
		server ui:4000;
        }


	server {
		listen 3000;

		location / {
			proxy_set_header  X-Real-IP  $remote_addr;
    			proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    			proxy_set_header Host $http_host;
    			proxy_pass http://app;
		}
	}
 
	server {
	listen 80;
         
		location / {
			proxy_pass http://node-app;
		}

	}
}

server.ts:

// Express server
const app = express();
[...]
app.listen(4000, () => {
  console.log('listening at 4000');
});

Let’s say that my public IP is 188.222.22.22 I can reach my Rails app at 188.222.22.22:3000 (using nginx as a proxy), I can reach my ui app at 188.222.22.22:4000 (without nginx) but I can not get UI at 188.222.22.22. I was trying with several configs and nothing works.

188.222.22.22 gives me 502 Bad Gateway, this is what I found in logs: 1 connect() failed (111: Connection refused) while connecting to upstream

Thanks!


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Hi there,

In the reverse proxy rule, you’ve defined http://node-app; however a few lines above that the UI service is defined as ui:

	listen 80;
         
		location / {
			proxy_pass http://node-app;
		}

	}

Make sure to use the same name as defined in your upstream. Otherwise, Nginx will not be able to resolve the hostname.

Hope that this helps!

Best,

Bobby