MongoDB数据库连接错误-Docker Compose

时间:2019-04-09 09:45:26

标签: node.js docker

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

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

我的应用程序结构如下

  • dist
    • 客户端
    • 服务器
  • 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下运行 客户端站点工作正常,但由于数据库连接错误而无法访问后端

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

  

无法加载资源:服务器响应状态为404   (未找到)

在我的控制台上,我只是

  

angular_1 | angular_1 | > proto@0.0.0开始:prod / app angular_1
  | > NODE_ENV =生产节点dist / server / server.js angular_1 |   angular_1 | Express服务器侦听端口8000 angular_1 |   数据库连接错误

1 个答案:

答案 0 :(得分:-1)

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

PS。但是,我始终建议使用ENV变量,因此您可以从外部设置这些内容,