gpt4 book ai didi

node.js - MongoDB 数据库连接错误 - Docker Compose

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:15 25 4
gpt4 key购买 nike

我已经构建了一个客户端服务器应用程序,并使用 MongoDB 作为我的数据库。

我想使用 docker-compose,但是在 docker-compose up 后出现数据库连接错误

我的应用程序结构如下所示

  • 距离
    • 客户端
    • 服务器
  • Dockerfile
  • docker-compose.yml
  • package.json

Dockerfile

# Create image based on the official Node 10 image from dockerhub
FROM node:10

# Create a directory where our app will be placed
RUN mkdir -p /app

# Change directory so that our commands run inside this new directory
WORKDIR /app

# Copy dependency definitions
COPY package*.json /app/

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /app/

# Expose the port the app runs in
EXPOSE 8000

# Serve the app
CMD ["npm", "run", "start:prod"]

docker.compose.yml

version: '2' # specify docker-compose version

# Define the services/containers to be run
services:
angular: # name of the first service
build: ./ # specify the directory of the Dockerfile
ports:
- "8000:8000" # specify port forwarding
links:
- database # link this service to the database service
database: # name of the third service
restart: always
image: mongo # specify image to build container from
container_name: mongo
ports:
- "27017:27017" # specify port forewarding

数据库

import * as mongoose from 'mongoose';

const server = 'database:27017'; // REPLACE WITH YOUR DB SERVER
const database = 'twitter';

export class Database {
constructor() {}

static connect() {
mongoose.connect(`mongodb://${server}/${database}`, {
useCreateIndex: true,
useNewUrlParser: true
}).then(() => {
console.log('Database connection successful');
})
.catch(err => {
console.error('Database connection error');
});
}
}

这里我将主机设置为databse而不是localhost

服务器

import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as path from 'path';
import * as cors from 'cors';
import { Routes } from './routes/twitter';


class App {

public app: express.Application;
public route: Routes = new Routes();

constructor() {
this.app = express();
this.config();
this.route.routes(this.app);
}

private config(): void {
this.app.use(cors());
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: false }));

if (this.app.get('env') === 'production') {
// loading the angular client folder or application
this.app.use(express.static(path.join(__dirname, '/../client')));
}
}

}

export default new App().app;

命令

docker-compose up

package.json 脚本

  "scripts": {
"ng": "ng",
"start": "concurrently --kill-others \"npm run server:run\" \"ng serve --proxy-config proxy.conf.json\"",
"server:run": "tsc -p ./server && concurrently \"tsc -w -p ./server\" \"nodemon dist/server/server.js\" ",
"build": "ng build --prod --output-path=dist/client && npm run server:build",
"server:build": "tsc -p ./server",
"copyfiles": "cp -R ai dist/server/routes",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"start:prod": "NODE_ENV=production node dist/server/server.js"
},

应用程序正在 localhost:8000 下运行客户端工作正常,但由于数据库连接错误,无法访问后端

在浏览器中我收到以下错误:

Failed to load resource: the server responded with a status of 404 (Not Found)

在我的控制台上我刚刚

angular_1 | angular_1 | > proto@0.0.0 start:prod /app angular_1
| > NODE_ENV=production node dist/server/server.js angular_1 | angular_1 | Express server listening on port 8000 angular_1 | Database connection error

最佳答案

我认为您的数据库 URL 不正确,因为 const server = 'database:27017'; 未从容器内部解析。当您使用 docker-compose 时,容器构建在默认网络上,因此您可以从 container_name 访问服务:如果您的 mongo 容器名为“mongo_db”,则在必须与 db 通信的服务中,url const server = 'mongo_db:27017';

PS。然而,我总是建议使用 ENV 变量,这样你就可以从外部设置这些东西,

关于node.js - MongoDB 数据库连接错误 - Docker Compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55589807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com