1

I'm trying to run node and nginx each inside their own docker containers and proxy from nginx to node. I tried the configuration below without docker at first and it worked. However when using docker it's not working and gives Status Code:502 Bad Gateway when trying to connect to http://localhost/.

node server

var http = require('http');
http.createServer(function (req, res) {
    res.setHeader('content-type', 'text/html');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Headers', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    res.end('<html>Hey</html>');
}).listen(3001);

docker-compose.yml

version: '3'
services:
  app:
    build: ./servers
  nginx:
    build: ./nginx
    depends_on: 
      - app
    links:
      - app
    volumes:
      - ./nginx/conf:/etc/nginx/conf.d:ro
    ports: 
      - 80:80

nginx conf

server {
        listen 80;
        listen [::]:80;

        location / {
                proxy_pass http://app;
        }
}

app dockerfile

FROM node:alpine
RUN mkdir /app/
COPY ./server.js /app
EXPOSE 3001
WORKDIR /app
CMD node server

nginx dockerfile

FROM nginx:alpine
RUN rm /etc/nginx/conf.d/*
5
  • Where does app in your NGINX config point to? Commented Jun 8, 2017 at 16:42
  • @robertklep it's the app service in docker-compose Commented Jun 8, 2017 at 16:43
  • 1
    I'm not very familiar with Docker, so I might be asking stupid questions ;D Is there a mapping somewhere to port 3001 on which the Node server is running (I see it's being exposed, but I don't see where NGINX is told to use it). Commented Jun 8, 2017 at 16:44
  • @robertklep Yes, you are right, I fixed the error. . Do you want to answer the question ? Commented Jun 8, 2017 at 16:51
  • you solved it, so you get to answer it (as you already did :) Commented Jun 8, 2017 at 18:25

1 Answer 1

1

This now looks like a stupid question but I had the misconception that docker linked containers to whatever ports it opened without specifying the port. It turns out all the example I followed used port 80 on the other side. Anyway, enough with justifying myself, all I had to do was make the js server listen on port 80.

http.createServer(function (req, res) {
   ...
}).listen(80);

Alternatively I believe I could have used port 3001 in nginx conf

    location / {
            proxy_pass http://app:3001;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.