我无法解决MongoParseError。
首先我尝试过
mongoose.connect(`mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});
使我最终遇到此错误
MongoParseError: Unescaped slash in userinfo section
然后我逃脱了所有的斜线
mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});
我最终遇到了无法解决的错误
MongoParseError: Invalid connection string
这是我的index.js
'use strict';
const mongoose = require('mongoose');
mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('ok');
});
const express = require('express');
// Constants
const PORT = 8080;
const HOST = 'localhost';
var kittySchema = new mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var silence = new Kitten({ name: 'Test1234' });
// App
const app = express();
app.get('/', (req, res) => {
res.send(silence.name);
});
app.listen(PORT);
console.log(`Running on http://${HOST}:${PORT}`);
这是docker-compose.yml
version: '3.7'
services:
web:
build: .
command: npm start
volumes:
- ./src:/usr/app/
- ./src/node_modules:/usr/app/node_modules
ports:
- 80:8080
environment:
DB_NAME: websitedb
DB_USER: /run/secrets/db_user
DB_PASSWORD: /run/secrets/db_password
secrets:
- db_user
- db_password
db:
image: mongo:latest
volumes:
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
ports:
- "27017:27017"
environment:
MONGO_INITDB_DATABASE: websitedb
MONGO_INITDB_ROOT_USERNAME_FILE: /run/secrets/db_user
MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_user
- db_password
volumes:
mongo:
secrets:
db_user:
file: ./db_user.txt
db_password:
file: ./db_password.txt
谁能告诉我我在做什么错?
答案 0 :(得分:2)
翻阅guide on managing secrets in docker compose,似乎所有秘密都作为安装在/run/secrets/SECRET_NAME
中的文件传递到了容器中,建议将路径作为环境变量传递给该文件,然后在您的应用中读取文件:
部署时,Docker会在服务中的/ run / secrets /下挂载文件。这些文件永远不会保留在磁盘中,而是在内存中进行管理。
每个服务都使用环境变量来指定服务应在哪里寻找该秘密数据。
您已将这些机密的路径作为process.env.DB_USER
传递,但是要获取实际机密,您需要读取文件:
const fs = require('fs');
const mongoose = require('mongoose');
let dbUser = fs.readFileSync(process.env.DB_USER);
let dbPassword = fs.readFileSync(process.env.DB_PASSWORD);
mongoose.connect(`mongodb://${dbUser}:${dbPassword}@db:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});