我如何使用docker-compose将nginx配置为nodejs(express)应用程序的反向代理

问题描述 投票:0回答:2

我正在尝试构建一个 docker-compose 文件,其中 nginx 作为 Nodejs 应用程序的反向代理。

总结一下我的想法是: 浏览器(localhost:8000) - > Nginx(端口:80) - >节点(端口:3000) - >返回我的“Hello World!”

我的文件:

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;
    }
}

节点/Dockerfile

FROM node:15

WORKDIR /usr/src/app

COPY index.js .

RUN npm install express

EXPOSE 3000

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

节点/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}`)
})

运行应用程序 -> docker-compose up -d --build

当然我错过了一些东西,但是我最近如何开始学习 docker、docker-compose 以及 nginx,我不明白,我做错了什么。

如果你们需要更多信息,请告诉我。

node.js docker nginx docker-compose nginx-reverse-proxy
2个回答
0
投票

我遇到了与你完全相同的问题,做同样的练习。

看了你的文件,看来问题出在你的

proxy_pass
。您正在输入您的
ìmage
,但您应该输入您的
service
名字。

尝试在您的

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
    }
}

然后运行测试一下

docker compose up -d --build

然后

curl localhost:8080

0
投票

您在 nginx.conf 文件中将 nginx 拼写成了 server_name。


© www.soinside.com 2019 - 2024. All rights reserved.