Vitor
Vitor

Reputation: 13

How could I configure a nginx as reverse proxy for a nodejs (express) app using docker-compose

I'm trying to build a docker-compose file with a nginx working as reverse proxy for a nodejs app.

To summary my idea is: Browser(localhost:8000) -> Nginx(port:80) -> Node(port:3000) -> return my "Hello World!"

My files:

docker-compose.yaml

version: '3'

services:

    app:
        build:
            context: ./node
            dockerfile: Dockerfile
        image: vitordarochacamargo/node
        container_name: node
        networks:
            - desafio-network

    nginx:
        build:
            context: ./nginx
            dockerfile: Dockerfile
        image: vitordarochacamargo/nginx
        container_name: nginx
        networks:
            - desafio-network
        ports:
            - "8000:80"

networks:
    desafio-network:
        driver: bridge

nginx/Dockerfile

FROM nginx:1.15.0-alpine

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d

EXPOSE 80

CMD ["tail", "-f", "/dev/null"]

nginx/nginx.conf

server {
    listen 80;
    server_name vitordarochacamargo/ngix;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         vitordarochacamargo/node:3000;
    }
}

node/Dockerfile

FROM node:15

WORKDIR /usr/src/app

COPY index.js .

RUN npm install express

EXPOSE 3000

CMD [ "node", "index.js" ]

node/index.js

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    res.send('<h1>Full Cycle Rocks!</h1>')
})

app.listen(port, () => {
    console.log(`listening at http://localhost:${port}`)
})

To run the app -> docker-compose up -d --build

Off course I am missing something, but how I start to study recently docker, docker-compose and also nginx, I can't figure out, what I'm doing wrong.

If you guys, need more information, please let me know.

Upvotes: 0

Views: 1011

Answers (2)

dombom
dombom

Reputation: 1

You misspelled nginx for server_name in your nginx.conf file.

Upvotes: 0

Bruno Habermann
Bruno Habermann

Reputation: 811

I had the exact same issue that your are having, doing the same exercise.

Reading your files, it seems that the problem is in your proxy_pass. You are putting your ìmage, but you should be putting your service name.

Try doing this in your nginx/nginx.conf:

server {
    listen 80;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         http://app:3000; # app is the name of your service in docker-compose.yml
    }
}

Then test it by running

docker compose up -d --build

Then

curl localhost:8080

Upvotes: 0

Related Questions