无法使用 docker compose 运行 mongoexpress

Ani*_*ari 9 mongodb node.js docker docker-compose mongo-express

这是我关于 Node js 和 docker 的第一篇文章,所以请耐心等待。我正在使用 docker-compose 运行 mongo 和 mongo Express 容器,但 mongo Express 没有运行。当我在没有 docker-compose 的情况下运行 mongo 和 mongo Express 时,它工作得很好。所以,我认为我在 docker-compose 或 Node js 代码中遇到了一些问题

\n

docker-compose.yaml

\n
version: '3'\nservices:\n  mongodb:\n    image: mongo\n    ports:\n      - 27017:27017\n    environment:\n      - MONGO_INITDB_ROOT_USERNAME=admin\n      - MONGO_INITDB_ROOT_PASSWORD=password\n  mongo-express:\n    image: mongo-express\n    ports:\n      - 8080:8081\n    environment:\n      - ME_CONFIG_MONGODB_ADMINUSERNAME=admin\n      - ME_CONFIG_MONGODB_ADMINPASSWORD=password\n      - ME_CONFIG_MONGODB_SERVER=mongodb\n
Run Code Online (Sandbox Code Playgroud)\n

服务器.js

\n
let express = require('express');\nlet path = require('path');\nlet fs = require('fs');\nlet MongoClient = require('mongodb').MongoClient;\nlet bodyParser = require('body-parser');\nlet app = express();\n\napp.use(bodyParser.urlencoded({\n  extended: true\n}));\napp.use(bodyParser.json());\n\napp.get('/', function (req, res) {\n    res.sendFile(path.join(__dirname, "index.html"));\n  });\n\napp.get('/profile-picture', function (req, res) {\n  let img = fs.readFileSync(path.join(__dirname, "images/profile-1.jpg"));\n  res.writeHead(200, {'Content-Type': 'image/jpg' });\n  res.end(img, 'binary');\n});\n\n// use when starting application locally\nlet mongoUrlLocal = "mongodb://admin:password@localhost:27017";\n\n// use when starting application as docker container\nlet mongoUrlDocker = "mongodb://admin:password@mongodb";\n\n// pass these options to mongo client connect request to avoid DeprecationWarning for current Server Discovery and Monitoring engine\nlet mongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };\n\n// "user-account" in demo with docker. "my-db" in demo with docker-compose\nlet databaseName = "my-db";\n\napp.post('/update-profile', function (req, res) {\n  let userObj = req.body;\n\n  MongoClient.connect(mongoUrlLocal, mongoClientOptions, function (err, client) {\n    if (err) throw err;\n\n    let db = client.db(databaseName);\n    userObj['userid'] = 1;\n\n    let myquery = { userid: 1 };\n    let newvalues = { $set: userObj };\n\n    db.collection("users").updateOne(myquery, newvalues, {upsert: true}, function(err, res) {\n      if (err) throw err;\n      client.close();\n    });\n\n  });\n  // Send response\n  res.send(userObj);\n});\n\napp.get('/get-profile', function (req, res) {\n  let response = {};\n  // Connect to the db\n  MongoClient.connect(mongoUrlLocal, mongoClientOptions, function (err, client) {\n    if (err) throw err;\n\n    let db = client.db(databaseName);\n\n    let myquery = { userid: 1 };\n\n    db.collection("users").findOne(myquery, function (err, result) {\n      if (err) throw err;\n      response = result;\n      client.close();\n\n      // Send response\n      res.send(response ? response : {});\n    });\n  });\n});\n\napp.listen(3000, function () {\n  console.log("app listening on port 3000!");\n});\n
Run Code Online (Sandbox Code Playgroud)\n

如果我运行docker ps我只能看到 mongo 正在运行

\n
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                                           NAMES\nd20c4784d316   mongo     "docker-entrypoint.s\xe2\x80\xa6"   43 seconds ago   Up 38 seconds   0.0.0.0:27017->27017/tcp, :::27017->27017/tcp   nodeapplications_mongodb_1\n
Run Code Online (Sandbox Code Playgroud)\n

当我使用以下命令运行 docker-compose 时,我会看到此日志,我怀疑存在问题。任何帮助表示赞赏

\n

docker-compose -f docker-compose.yaml up

\n

日志

\n
mongo-express_1  | Welcome to mongo-express\nmongo-express_1  | ------------------------\nmongo-express_1  | \nmongo-express_1  | \nmongo-express_1  | (node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.\nmongo-express_1  | Could not connect to database using connectionString: mongodb://admin:password@mongodb:27017/"\nmongo-express_1  | (node:7) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [mongodb:27017] on first connect [Error: connect ECONNREFUSED 172.19.0.3:27017\nmongo-express_1  |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {\nmongo-express_1  |   name: 'MongoNetworkError'\nmongo-express_1  | }]\nmongo-express_1  |     at Pool.<anonymous> (/node_modules/mongodb/lib/core/topologies/server.js:438:11)\nmongo-express_1  |     at Pool.emit (events.js:314:20)\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/pool.js:562:14\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/pool.js:995:11\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/connect.js:32:7\nmongo-express_1  |     at callback (/node_modules/mongodb/lib/core/connection/connect.js:280:5)\nmongo-express_1  |     at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connect.js:310:7)\nmongo-express_1  |     at Object.onceWrapper (events.js:421:26)\nmongo-express_1  |     at Socket.emit (events.js:314:20)\nmongo-express_1  |     at emitErrorNT (internal/streams/destroy.js:92:8)\nmongo-express_1  |     at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)\nmongo-express_1  |     at processTicksAndRejections (internal/process/task_queues.js:84:21)\nmongo-express_1  | (node:7) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\n
Run Code Online (Sandbox Code Playgroud)\n

正如@Blunderchips更新 1所建议的

\n

服务器.js

\n
let express = require('express');\nlet path = require('path');\nlet fs = require('fs');\nlet MongoClient = require('mongodb').MongoClient;\nlet bodyParser = require('body-parser');\nlet app = express();\n\nconst dbServer = process.env.ME_CONFIG_MONGODB_SERVER;\nconst dbPassword = process.env.ME_CONFIG_MONGODB_ADMINPASSWORD;\nconst dbUserName = process.env.ME_CONFIG_MONGODB_ADMINUSERNAME;\nconst dbPort = process.env.ME_CONFIG_MONGODB_PORT;\n\napp.use(bodyParser.urlencoded({\n  extended: true\n}));\napp.use(bodyParser.json());\n\napp.get('/', function (req, res) {\n    res.sendFile(path.join(__dirname, "index.html"));\n  });\n\napp.get('/profile-picture', function (req, res) {\n  let img = fs.readFileSync(path.join(__dirname, "images/profile-1.jpg"));\n  res.writeHead(200, {'Content-Type': 'image/jpg' });\n  res.end(img, 'binary');\n});\n\n// use when starting application locally\n//let mongoUrlLocal = "mongodb://admin:password@localhost:27017";\n\n// use when starting application as docker container\nlet mongoUrlDocker = `mongodb://${dbUserName}:${dbPassword}@${dbServer}:${dbPort}`;//"mongodb://admin:password@mongodb:27017";//"mongodb://admin:password@mongodb";\n\n// pass these options to mongo client connect request to avoid DeprecationWarning for current Server Discovery and Monitoring engine\nlet mongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };\n\n// "user-account" in demo with docker. "my-db" in demo with docker-compose\nlet databaseName = "my-db";\n\napp.post('/update-profile', function (req, res) {\n  let userObj = req.body;\n\n  MongoClient.connect(mongoUrlDocker, mongoClientOptions, function (err, client) {\n    if (err) throw err;\n\n    let db = client.db(databaseName);\n    userObj['userid'] = 1;\n\n    let myquery = { userid: 1 };\n    let newvalues = { $set: userObj };\n\n    db.collection("users").updateOne(myquery, newvalues, {upsert: true}, function(err, res) {\n      if (err) throw err;\n      client.close();\n    });\n\n  });\n  // Send response\n  res.send(userObj);\n});\n\napp.get('/get-profile', function (req, res) {\n  let response = {};\n  // Connect to the db\n  MongoClient.connect(mongoUrlDocker, mongoClientOptions, function (err, client) {\n    if (err) throw err;\n\n    let db = client.db(databaseName);\n\n    let myquery = { userid: 1 };\n\n    db.collection("users").findOne(myquery, function (err, result) {\n      if (err) throw err;\n      response = result;\n      client.close();\n\n      // Send response\n      res.send(response ? response : {});\n    });\n  });\n});\n\napp.listen(3000, function () {\n  console.log("app listening on port 3000!");\n});\n
Run Code Online (Sandbox Code Playgroud)\n

docker-compose.yaml

\n
version: '3'\nservices:\n  mongodb:\n    image: mongo\n    ports:\n      - 27017:27017\n    environment:\n      - MONGO_INITDB_ROOT_USERNAME=admin\n      - MONGO_INITDB_ROOT_PASSWORD=password\n  mongo-express:\n    image: mongo-express\n    ports:\n      - 8080:8081\n    environment:\n      - ME_CONFIG_MONGODB_ADMINUSERNAME=admin\n      - ME_CONFIG_MONGODB_ADMINPASSWORD=password\n      - ME_CONFIG_MONGODB_SERVER=mongodb\n    links: \n        - mongodb:mongodb\n
Run Code Online (Sandbox Code Playgroud)\n

我仍然看不到 mongo Express 运行

\n
docker ps\nCONTAINER ID   IMAGE     COMMAND                  CREATED              STATUS              PORTS                                           NAMES\n23428dc0c3a1   mongo     "docker-entrypoint.s\xe2\x80\xa6"   About a minute ago   Up About a minute   0.0.0.0:27017->27017/tcp, :::27017->27017/tcp   nodeapplications_mongodb_1\n
Run Code Online (Sandbox Code Playgroud)\n

日志

\n
mongo-express_1  | Welcome to mongo-express\nmongo-express_1  | ------------------------\nmongo-express_1  | \nmongo-express_1  | \nmongo-express_1  | (node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.\nmongo-express_1  | Could not connect to database using connectionString: mongodb://admin:password@mongodb:27017/"\nmongo-express_1  | (node:7) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [mongodb:27017] on first connect [Error: connect ECONNREFUSED 172.23.0.2:27017\nmongo-express_1  |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {\nmongo-express_1  |   name: 'MongoNetworkError'\nmongo-express_1  | }]\nmongo-express_1  |     at Pool.<anonymous> (/node_modules/mongodb/lib/core/topologies/server.js:438:11)\nmongo-express_1  |     at Pool.emit (events.js:314:20)\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/pool.js:562:14\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/pool.js:995:11\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/connect.js:32:7\nmongo-express_1  |     at callback (/node_modules/mongodb/lib/core/connection/connect.js:280:5)\nmongo-express_1  |     at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connect.js:310:7)\nmongo-express_1  |     at Object.onceWrapper (events.js:421:26)\nmongo-express_1  |     at Socket.emit (events.js:314:20)\nmongo-express_1  |     at emitErrorNT (internal/streams/destroy.js:92:8)\nmongo-express_1  |     at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)\nmongo-express_1  |     at processTicksAndRejections (internal/process/task_queues.js:84:21)\nmongo-express_1  | (node:7) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\nmongo-express_1  | (node:7) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n
Run Code Online (Sandbox Code Playgroud)\n

更新2

\n
let express = require('express');\nlet path = require('path');\nlet fs = require('fs');\nlet MongoClient = require('mongodb').MongoClient;\nlet bodyParser = require('body-parser');\nlet app = express();\n\napp.use(bodyParser.urlencoded({\n  extended: true\n}));\napp.use(bodyParser.json());\n\napp.get('/', function (req, res) {\n    res.sendFile(path.join(__dirname, "index.html"));\n  });\n\napp.get('/profile-picture', function (req, res) {\n  let img = fs.readFileSync(path.join(__dirname, "images/profile-1.jpg"));\n  res.writeHead(200, {'Content-Type': 'image/jpg' });\n  res.end(img, 'binary');\n});\n\n// use when starting application locally\n//let mongoUrlLocal = "mongodb://admin:password@localhost:27017";\n\n// use when starting application as docker container\nlet mongoUrlDocker = "mongodb://admin:password@mongodb:27017";\n\n// pass these options to mongo client connect request to avoid DeprecationWarning for current Server Discovery and Monitoring engine\nlet mongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };\n\n// "user-account" in demo with docker. "my-db" in demo with docker-compose\nlet databaseName = "my-db";\n\napp.post('/update-profile', function (req, res) {\n  let userObj = req.body;\n\n  MongoClient.connect(mongoUrlDocker, mongoClientOptions, function (err, client) {\n    if (err) throw err;\n\n    let db = client.db(databaseName);\n    userObj['userid'] = 1;\n\n    let myquery = { userid: 1 };\n    let newvalues = { $set: userObj };\n\n    db.collection("users").updateOne(myquery, newvalues, {upsert: true}, function(err, res) {\n      if (err) throw err;\n      client.close();\n    });\n\n  });\n  // Send response\n  res.send(userObj);\n});\n\napp.get('/get-profile', function (req, res) {\n  let response = {};\n  // Connect to the db\n  MongoClient.connect(mongoUrlDocker, mongoClientOptions, function (err, client) {\n    if (err) throw err;\n\n    let db = client.db(databaseName);\n\n    let myquery = { userid: 1 };\n\n    db.collection("users").findOne(myquery, function (err, result) {\n      if (err) throw err;\n      response = result;\n      client.close();\n\n      // Send response\n      res.send(response ? response : {});\n    });\n  });\n});\n\napp.listen(3000, function () {\n  console.log("app listening on port 3000!");\n});\n
Run Code Online (Sandbox Code Playgroud)\n

更新3

\n

docker 撰写

\n
version: '3'\nservices:\n  mongodb:\n    image: mongo\n    ports:\n      - 27017:27017\n    environment:\n      - MONGO_INITDB_ROOT_USERNAME=admin\n      - MONGO_INITDB_ROOT_PASSWORD=password\n  mongo-express:\n    image: mongo-express\n    ports:\n      - 8080:8081\n    environment:\n      - ME_CONFIG_MONGODB_ADMINUSERNAME=admin\n      - ME_CONFIG_MONGODB_ADMINPASSWORD=password\n      - ME_CONFIG_MONGODB_SERVER=mongodb\n    links: \n        - mongodb:mongodb\n    restart: on-failure\n
Run Code Online (Sandbox Code Playgroud)\n

完整日志

\n
 mongo-express_1  | Welcome to mongo-express\nmongo-express_1  | ------------------------\nmongo-express_1  | \nmongo-express_1  | \nmongodb_1        | {"t":{"$date":"2021-07-04T10:41:58.806+00:00"},"s":"I",  "c":"STORAGE",  "id":22318,   "ctx":"SignalHandler","msg":"Shutting down session sweeper thread"}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:41:58.806+00:00"},"s":"I",  "c":"STORAGE",  "id":22319,   "ctx":"SignalHandler","msg":"Finished shutting down session sweeper thread"}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:41:58.807+00:00"},"s":"I",  "c":"STORAGE",  "id":22322,   "ctx":"SignalHandler","msg":"Shutting down checkpoint thread"}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:41:58.807+00:00"},"s":"I",  "c":"STORAGE",  "id":22323,   "ctx":"SignalHandler","msg":"Finished shutting down checkpoint thread"}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:41:58.807+00:00"},"s":"I",  "c":"STORAGE",  "id":4795902, "ctx":"SignalHandler","msg":"Closing WiredTiger","attr":{"closeConfig":"leak_memory=true,"}}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:41:58.810+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"SignalHandler","msg":"WiredTiger message","attr":{"message":"[1625395318:810568][28:0x7f50eec9b700], close_ckpt: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 48, snapshot max: 48 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0)"}}\nmongo-express_1  | (node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.\nmongo-express_1  | Could not connect to database using connectionString: mongodb://admin:password@mongodb:27017/"\nmongo-express_1  | (node:7) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [mongodb:27017] on first connect [Error: connect ECONNREFUSED 172.27.0.2:27017\nmongo-express_1  |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {\nmongo-express_1  |   name: 'MongoNetworkError'\nmongo-express_1  | }]\nmongo-express_1  |     at Pool.<anonymous> (/node_modules/mongodb/lib/core/topologies/server.js:438:11)\nmongo-express_1  |     at Pool.emit (events.js:314:20)\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/pool.js:562:14\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/pool.js:995:11\nmongo-express_1  |     at /node_modules/mongodb/lib/core/connection/connect.js:32:7\nmongo-express_1  |     at callback (/node_modules/mongodb/lib/core/connection/connect.js:280:5)\nmongo-express_1  |     at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connect.js:310:7)\nmongo-express_1  |     at Object.onceWrapper (events.js:421:26)\nmongo-express_1  |     at Socket.emit (events.js:314:20)\nmongo-express_1  |     at emitErrorNT (internal/streams/destroy.js:92:8)\nmongo-express_1  |     at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)\nmongo-express_1  |     at processTicksAndRejections (internal/process/task_queues.js:84:21)\nmongo-express_1  | (node:7) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\nmongo-express_1  | (node:7) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\nmongodb_1        | {"t":{"$date":"2021-07-04T10:42:00.871+00:00"},"s":"I",  "c":"STORAGE",  "id":4795901, "ctx":"SignalHandler","msg":"WiredTiger closed","attr":{"durationMillis":2064}}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:42:00.871+00:00"},"s":"I",  "c":"STORAGE",  "id":22279,   "ctx":"SignalHandler","msg":"shutdown: removing fs lock..."}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:42:00.872+00:00"},"s":"I",  "c":"-",        "id":4784931, "ctx":"SignalHandler","msg":"Dropping the scope cache for shutdown"}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:42:00.873+00:00"},"s":"I",  "c":"FTDC",     "id":4784926, "ctx":"SignalHandler","msg":"Shutting down full-time data capture"}\nmongodb_1        | {"t":{"$date":"2021-07-04T10:42:00.873+00:00"},"s":"I",  "c":"FTDC",     "id":20626,   "ctx":"SignalHandler","msg":"Shutting down f

Ani*_*ari 19

正如@David Maze 建议的那样,添加restart: except-stopped它有效

version: '3'
services:
  mongodb:
    image: mongo
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
  mongo-express:
    image: mongo-express
    ports:
      - 8081:8081
    environment:
      - ME_CONFIG_MONGODB_ADMINUSERNAME=admin
      - ME_CONFIG_MONGODB_ADMINPASSWORD=password
      - ME_CONFIG_MONGODB_SERVER=mongodb
    restart: unless-stopped
Run Code Online (Sandbox Code Playgroud)

  • 我正在 techworkwithNana 上做同样的课程,也遇到了同样的问题。我不明白为什么教练没有收到这个错误?添加 restart: except-stopped 如何解决该问题? (4认同)