Load Balacing Nodejs application using Nginx and D

2019-08-31 16:20发布

问题:

I am following this YouTube tutorial on how to configure Nginx Server on Docker

/docker_compose.yml

version: '3'
services:
  nodecluster:
        build: nodecluster
        ports:
        - "49160:8000"
  proxy:
    build: proxy
    ports:
    - "80:80"  

nodecluster/Dockerfile

FROM node:8

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm install --only=production

# Bundle app source
COPY . .

EXPOSE 8000
CMD [ "npm", "start" ]

proxy/Dockerfile

FROM nginx:alpine

RUN rm /etc/nginx/conf.d/*

COPY proxy.conf /etc/nginx/conf .d/

proxy/proxy.conf

listen 80;
server {
    location / {
        proxy_pass http://nodecluster;
    }
}

Docker Command prompt Details

But When I hit localhost instead of in the tutorial I am getting nginx 502 bad gateway error . I tried localhost:49160 it is working and giving normal input. So how to correctly map the incoming request to the nodecluster

回答1:

It looks like you need to set your nginx config to use the proper port:

listen 80;
server {
    location / {
        proxy_pass http://nodecluster:8000;
    }
}

And you shouldn't need to expose port 8000 if you only wish to expose the proxy (nginx) to the outside world and have all the connections through it since by default they're included together in an isolated network.

Does that help?