我尝试在docker容器中使用express和MongoDB创建一个小API,但无法连接到数据库:
下面是我连接脚本:
const mongoose = require('mongoose');
const result = require('dotenv').config();
const logger = require('../logger/api.logger');
const { DB_USER, DB_PASS, DB_HOST, DB_PORT, DB_NAME } = process.env
const connect = () => {
const url = `mongodb://@${DB_HOST}:${DB_PORT}/${DB_NAME}`;
logger.info("CONNECTION_STRING = " + url);
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: process.env.DB_NAME,
})
mongoose.connection.once("open", async () => {
logger.info("Connected to database");
});
mongoose.connection.on("error", (err) => {
logger.error("Error connecting to database ", err);
});
}
const disconnect = () => {
if (!mongoose.connection) {
return;
}
mongoose.disconnect();
mongoose.once("close", async () => {
console.log("Diconnected to database");
});
};
module.exports = {
connect,
disconnect
}
.env文件:
APP_PORT=3333
DB_NAME=first_db
DB_PORT=2717
DB_HOST=db_container
app.js文件:
const express = require('express');
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
// Routes
const router = require('./routes/router');
app.use(router);
// DB Connection
const database = require('./database/connection');
database.connect();
module.exports = app;
docker-compose文件:
version: '3.9'
services:
# Mongo DB
mongo_db:
image: mongo:latest
container_name: db_container
restart: always
ports:
- '${DB_PORT}:2717'
volumes:
- mongo_db:/data/db
environment:
MONGO_INITDB_DATABASE: ${DB_NAME}
MONGO_INITDB_ROOT_USERNAME: ${DB_USER}
MONGO_INITDB_ROOT_PASSWORD: ${DB_PASS}
# Node API Service
api:
build: .
ports:
- '${APP_PORT}:${APP_PORT}'
depends_on:
- mongo_db
volumes:
- .:/usr/src/
env_file:
- .env
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
volumes:
mongo_db: {}
但是每次我构建docker镜像并尝试运行它时,都会出现以下错误:
db_container | {"t":{"$date":"2023-03-17T20:36:51.205+00:00"},"s":"I", "c":"NETWORK", "id":23015, "ctx":"listener","msg":"Listening on","attr":{"address":"0.0.0.0"}}
db_container | {"t":{"$date":"2023-03-17T20:36:51.205+00:00"},"s":"I", "c":"NETWORK", "id":23016, "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}
docker-api-1 | MongooseServerSelectionError: connect ECONNREFUSED 172.23.0.2:2717
docker-api-1 | at _handleConnectionErrors (/app/node_modules/mongoose/lib/connection.js:755:11)
docker-api-1 | at NativeConnection.openUri (/app/node_modules/mongoose/lib/connection.js:730:11)
docker-api-1 | at runNextTicks (node:internal/process/task_queues:60:5)
docker-api-1 | at listOnTimeout (node:internal/timers:537:9)
docker-api-1 | at process.processTimers (node:internal/timers:511:7)
docker-api-1 | at async Object.connect (/app/src/database/connection.js:82:7) {
docker-api-1 | reason: TopologyDescription {
docker-api-1 | type: 'Unknown',
docker-api-1 | servers: Map(1) { 'db_container:2717' => [ServerDescription] },
docker-api-1 | stale: false,
docker-api-1 | compatible: true,
docker-api-1 | heartbeatFrequencyMS: 10000,
docker-api-1 | localThresholdMS: 15,
docker-api-1 | setName: null,
docker-api-1 | maxElectionId: null,
docker-api-1 | maxSetVersion: null,
docker-api-1 | commonWireVersion: 0,
docker-api-1 | logicalSessionTimeoutMinutes: null
docker-api-1 | },
docker-api-1 | code: undefined
docker-api-1 | }
docker-api-1 exited with code 1
1条答案
按热度按时间fnvucqvd1#
我看到你的
.env
文件有两个问题:DB_PORT=2717
- Mongo端口是27017,你在那里丢失了一个'0';DB_HOST=db_container
-在Compose中,服务名是主机名,而不是容器名,因此必须是DB_HOST=mongo_db
。此外,除非你想从主机访问Mongo,否则这不是必需的: