如何在两个容器之间进行通信:nginx 和 nodejs

how to communicate between two containers: nginx and nodjs

我很难弄清楚如何从 nginx 容器 proxypass 进入 nodejs 容器。

在我看来 http://localhost:3000 会落在 nginx 容器内...所以我认为这个设置是有意义的:

nginx容器:

podman run -d \
            --name nginx.main \
            -p 0.0.0.0:8081:8080 \
            -p 0.0.0.0:4431:4430 \
            -p 0.0.0.0:3001:3000 \
            -u root \
            -v /home/_secrets/certbot/_certs:/etc/nginx/_cert \
            -v /home/mee/_volumes/nginx_main:/etc/nginx \
            nginx

nodjs容器:

podman run -d \
            -v /home/mee/dev/abd/:/usr/src/app -w /usr/src/app \
            -p 3000:3000 \
            --name next.dev node:latest \
            npm run dev

firewalld,路由从30013000

sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --add-port=3001/tcp --permanent
sudo firewall-cmd --permanent \
   --zone=mee_fd \
   --add-forward-port=port=3001:proto=tcp:toport=3000
sudo firewall-cmd --reload

nginx 配置:

location / {
                proxy_pass http://localhost:3000;
                add_header X-Frame-Options "SAMEORIGIN" always;
                add_header X-XSS-Protection "1; mode=block" always;
                add_header X-Content-Type-Options "nosniff" always;
                add_header Referrer-Policy "no-referrer-when-downgrade" always;
                add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
                # add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
                # enable strict transport security only if you understand the implications
        }

真的不确定这应该如何沟通...我尝试使用 ipaddress 而不是 'localhost',但我得到了相同的响应。

谢谢

要允许容器之间进行通信,您需要设置共享网络,例如在 .yaml 中(这可以在 ci 中完成,在 .yaml 中报告只是为了代码):

version: '2'
services:
proxy:
build: ./
networks:
- example1
- example2
ports:
- 80:80
- 443:443

networks:
example1:
external:
name: example1_default
example2:
external:
name: example2_default

然后在你的 nginx 配置中:

location / {
                proxy_pass http://myServiceName:3000; <-- note is not localhost but the name of node service
                add_header X-Frame-Options "SAMEORIGIN" always;
                add_header X-XSS-Protection "1; mode=block" always;
                add_header X-Content-Type-Options "nosniff" always;
                add_header Referrer-Policy "no-referrer-when-downgrade" always;
                add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
                # add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
                # enable strict transport security only if you understand the implications
        }

告诉我