NodeJS MongoError:无法使用docker-compose连接到服务器

luaexgnf  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(163)

这是我的docker-compose。yaml:

version: '3'
services:
  app:
    image: chaseloyd/portfolio-site:latest
    ports:
      - "3000:3000"
  mongo2:
    image: mongo
    container_name: mongo2
    restart: always
    ports:
      - "27018:27018"
  game:
    image: chaseloyd/multiplayer-game:latest
    ports:
      - "3030:3030"
    links:
      - "mongo2"

下面是我代码:

var mongoose = require("mongoose");
mongoose.connect("mongodb://mongo2:27018/db");

错误:

MongoError: failed to connect to server [mongo2:27018] on first connect [MongoError: connect ECONNREFUSED 172.19.0.3:27018]

我希望它能成功连接。这个容器在某个时候起了作用。我正在尝试重新创建docker-compose文件,该文件成功地将这些容器绑定在一起。谢谢你的时间。你可以很容易地试用你的机器。

nhn9ugyo

nhn9ugyo1#

为了让Docker容器通过名称相互通信,应该创建一个docker network。在这种情况下,容器appmongo2以及game(如有必要)应留在同一网络上,以便它们相互通信。你可以建立这样的网络

version: '3'
services:
  app:
    image: chaseloyd/portfolio-site:latest
    ports:
      - "3000:3000"
    networks:
      - test-network

  mongo2:
    image: mongo
    container_name: mongo2
    restart: always
    ports:
      - "27018:27018"
    networks:
      - test-network

  game:
    image: chaseloyd/multiplayer-game:latest
    ports:
      - "3030:3030"
    links:
      - "mongo2"
    networks:
      - test-network
networks:
  test-network:

相关问题