使用 docker-compose 运行时 Mongodb 连接失败

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

这是我的 server.js 文件:

let path = require('path');
let fs = require('fs');
let MongoClient = require('mongodb').MongoClient;
let bodyParser = require('body-parser');
let app = express();

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, "index.html"));
  });

  
app.get('/profile-picture', function (req, res) {
  let img = fs.readFileSync(path.join(__dirname, "images/profile-1.jpg"));
  res.writeHead(200, {'Content-Type': 'image/jpg' });
  res.end(img, 'binary');
});
let mongoUrlLocal = "mongodb://admin:password@localhost:27017";
let mongoUrlDocker = "mongodb://admin:password@mongodb";
let mongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };
let databaseName = "user-account";

app.post('/update-profile', function (req, res) {
  let userObj = req.body;
    MongoClient.connect('mongodb://localhost:8080', function (err, client) {
    if (err) throw err;

    let db = client.db(databaseName);
    userObj['userid'] = 1;

    let myquery = { userid: 1 };
    let newvalues = { $set: userObj };

    db.collection("users").updateOne(myquery, newvalues, {upsert: true}, function(err, res) {
      if (err) throw err;
      client.close();
    });

  });
  // Send response
  res.send(userObj);
});

app.get('/get-profile', function (req, res) {
  let response = {};
  // Connect to the db
    MongoClient.connect('mongodb://admin:password@localhost:8080', function (err, client) {
    if (err) throw err;

    let db = client.db(databaseName);

    let myquery = { userid: 1 };

    db.collection("users").findOne(myquery, function (err, result) {
      if (err) throw err;
      response = result;
      client.close();

      // Send response
      res.send(response ? response : {});
    });
  });
});

app.listen(3000, function () {
  console.log("app listening on port 3000!");
});

这是我的 docker-compose.yml 文件

version: '3'
services:
  # my-app:
  # image: ${docker-registry}/my-app:1.0
  # ports:
  # - 3000:3000
  mongodb:
    image: mongo
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
    volumes:
      - mongo-data:/data/db
  mongo-express:
    image: mongo-express
    restart: always # fixes MongoNetworkError when mongodb is not ready when mongo-express starts
    ports:
      - 8080:8081
    environment:
      - ME_CONFIG_MONGODB_ADMINUSERNAME=admin
      - ME_CONFIG_MONGODB_ADMINPASSWORD=password
      - ME_CONFIG_MONGODB_SERVER=mongodb
volumes:
  mongo-data:
    driver: local

这是 Dockerfile:


ENV MONGO_DB_USERNAME=admin \
    MONGO_DB_PWD=password

RUN mkdir -p /home/app

COPY ./app /home/app
WORKDIR /home/app
RUN npm install
CMD ["node", "server.js"]

当我运行

docker-compose -f docker-compose.yml up
时出现此错误:

ms","Start up the replication coordinator":"6 ms","Start transport layer":"2 ms","_initAndListen total elapsed time":"909 ms"}}}}        
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:27:38 UTC 2024 retrying to connect to mongo:27017 (2/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:27:44 UTC 2024 retrying to connect to mongo:27017 (3/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:27:50 UTC 2024 retrying to connect to mongo:27017 (4/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:27:56 UTC 2024 retrying to connect to mongo:27017 (5/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Name does not resolve
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:28:00 UTC 2024 retrying to connect to mongo:27017 (6/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Name does not resolve
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:28:05 UTC 2024 retrying to connect to mongo:27017 (7/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:28:11 UTC 2024 retrying to connect to mongo:27017 (8/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:28:17 UTC 2024 retrying to connect to mongo:27017 (9/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | Wed Apr  3 01:28:23 UTC 2024 retrying to connect to mongo:27017 (10/10)
mongo-express-1  | /docker-entrypoint.sh: line 15: mongo: Try again
mongo-express-1  | /docker-entrypoint.sh: line 15: /dev/tcp/mongo/27017: Invalid argument
mongo-express-1  | No custom config.js found, loading config.default.js
mongo-express-1  | Welcome to mongo-express 1.0.2

并且无法使用

node server.js
在端口 3000 运行此应用程序 它进入应用程序在端口 3000 侦听,但在浏览器上它都是空的。 参考:https://www.youtube.com/watch?v=3c-iBn73dDE&t=7223s

node.js mongodb docker express docker-compose
1个回答
0
投票

从根本上来说,

mongo-express
Docker 镜像是有问题的。

虽然

mongo-express
应用程序本身将使用
ME_CONFIG_MONGODB_SERVER
(如果已设置)(并且会更喜欢使用
ME_CONFIG_MONGODB_URL
),但入口点脚本 (
/docker-entrypoint.sh
) 使用
ME_CONFIG_MONDODB_URL
。它包含以下代码

if [[ "$ME_CONFIG_MONGODB_URL" != *,* ]]; then
    work=$ME_CONFIG_MONGODB_URL
    # Remove the scheme (should be "mongodb://" or "mongodb+srv://").
    work=${work#*://}
    # Remove the path component of the URL (should just be a "/").
    work=${work%%/*}
    # Remove the userinfo.
    work=${work#*@}
    if [[ "$work" = *:* ]]; then
        # Match the host.
        host=${work%:*}
        # Match the port.
        port=${work#*:}
    else
        host=$work
        port=27017
    fi

    # wait for the mongo server to be available
    echo "Waiting for $host:$port..."
    wait_tcp_port "$host" "$port" "${ME_CONFIG_CONNECT_RETRIES:-10}"
fi

图像还为

ME_CONFIG_MONGODB_URL
设置了默认值
mongodb://mongo:27017
。由于您正在设置
ME_CONFIG_MONGODB_SERVER
没有 设置
ME_CONFIG_MONGODB_URL
,因此入口点会根据该默认值陷入等待连接到服务器
mongo
的状态。

我们可以通过为

ME_CONFIG_MONGODB_URL
提供适当的值来解决这个问题:

services:
  mongodb:
    image: mongo
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password
    volumes:
      - mongo-data:/data/db
  mongo-express:
    image: mongo-express
    restart: always # fixes MongoNetworkError when mongodb is not ready when mongo-express starts
    ports:
      - 8080:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: admin
      ME_CONFIG_MONGODB_ADMINPASSWORD: password
      ME_CONFIG_MONGODB_SERVER: mongodb
      ME_CONFIG_MONGODB_URL: mongodb://mongodb:27017
volumes:
  mongo-data:

上面的撰写文件成功调出

mongo-express

您还可以通过将

mongodb
服务重命名为
mongo
来解决此问题,这将使其与默认值匹配。

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