Docker从一个容器调用另一个容器(拒绝连接)

时间:2018-12-25 06:56:14

标签: node.js docker networking docker-compose

我有两个NodeJS服务的容器和一个Nginx的反向代理容器。

我在端口80上设置了NINNX,因此可以通过我的浏览器上的localhost公开访问

我还使用反向代理将proxy_pass传递给每个负责的服务。

  location /api/v1/service1/ {
    proxy_pass http://service1:3000/;
  }

  location /api/v1/service2/ {
    proxy_pass http://service2:3000/;
  }

在我的服务1中,有一个axios模块希望通过向localhost/api/v1/service2发出请求来调用服务2

但是,它表示连接被拒绝。我怀疑服务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

即使使用网络后,它仍然显示ECONNREFUSED。
请帮忙。

2 个答案:

答案 0 :(得分:0)

尝试在depends_on的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
    depends_on:
      - service1
      - service2

networks:
  backend:
    driver: bridge

这将确保在nginx容器尝试连接到它们之前先运行这两个服务。也许连接被拒绝是因为Nginx容器由于执行conf文件并连接到后端时没有找到两个正在运行的服务而不断崩溃。

答案 1 :(得分:-2)

我相信您还需要在每个服务上公开端口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
相关问题