Node.js 容器中的Docker调用另一个容器(连接被拒绝)
我有两个NodeJS服务的容器和一个反向代理的Nginx 我在端口80上制作了NGINX,因此可以通过浏览器上的localhost公开使用 我还使用反向代理来代理传递给每个负责的服务Node.js 容器中的Docker调用另一个容器(连接被拒绝),node.js,docker,networking,docker-compose,Node.js,Docker,Networking,Docker Compose,我有两个NodeJS服务的容器和一个反向代理的Nginx 我在端口80上制作了NGINX,因此可以通过浏览器上的localhost公开使用 我还使用反向代理来代理传递给每个负责的服务 location /api/v1/service1/ { proxy_pass http://service1:3000/; } location /api/v1/service2/ { proxy_pass http://service2:3000/; } 在我的服务1中,有一
location /api/v1/service1/ {
proxy_pass http://service1:3000/;
}
location /api/v1/service2/ {
proxy_pass http://service2:3000/;
}
在我的服务1中,有一个axios模块希望通过向localhost/api/v1/service2
但是,它说连接被拒绝了。我怀疑服务1中的localhost
是否指的是它的容器,而不是docker主机
version: '3'
services:
service1:
build: './service1'
networks:
- backend
service2:
build: './service2'
networks:
- backend
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
networks:
- backend
networks:
backend:
driver: bridge
即使使用了网络,它仍然会显示EconRefused。请提供帮助。我认为您还需要在每个服务上公开端口3000。如下图所示:
version: '3'
services:
service1:
build: './service1'
expose:
- "3000"
networks:
- backend
service2:
build: './service2'
expose:
- "3000"
networks:
- backend
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
networks:
- backend
networks:
backend:
driver: bridge
version: '3'
services:
service1:
build: './service1'
expose:
- "3000"
networks:
- backend
service2:
build: './service2'
expose:
- "3000"
networks:
- backend
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
networks:
- backend
depends_on:
- service1
- service2
networks:
backend:
driver: bridge
尝试在docker compose文件中为
nginx
添加依赖项,如下所示:
version: '3'
services:
service1:
build: './service1'
expose:
- "3000"
networks:
- backend
service2:
build: './service2'
expose:
- "3000"
networks:
- backend
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
networks:
- backend
networks:
backend:
driver: bridge
version: '3'
services:
service1:
build: './service1'
expose:
- "3000"
networks:
- backend
service2:
build: './service2'
expose:
- "3000"
networks:
- backend
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
networks:
- backend
depends_on:
- service1
- service2
networks:
backend:
driver: bridge
这将确保在nginx容器尝试连接到这两个服务之前,这两个服务都先运行。可能是由于nginx容器在执行其conf文件并连接到后端时未找到正在运行的两个服务而导致连接被拒绝。正如您所注意的,server1容器的localhost
就是server1容器。您可能需要配置主机名。@DavidMaze知道如何配置吗?那么,我应该用它吗?我正在尝试连接到localhost,因此当我更改API服务时,它会自动更改,而不会将所有内容重命名为您不尝试连接到localhost
(“此容器”),您正在尝试连接到其他地方运行的服务。如果源代码中有硬编码的主机名,则需要对其进行配置,最有可能的方式是从环境变量中获取其值。@DavidMaze您最好发布一个答案,以便我可以接受。expose:
在Docker networks的世界中几乎什么都做不了。(它会影响过时的容器间链接和Docker选择主机端口的默认发布机制,两者都不是很有用。)@DavidMaze你说得太对了。暴露端口不会解决问题。谢谢回答。无论如何,这不是我的问题。两项服务都已启动。我想做的是:一个容器如何引用主主机(通过连接到主主机中的localhost,而不是容器)?