简体   繁体   English

docker-compose:nodejs 容器未与 postgres 容器通信

[英]docker-compose: nodejs container not communicating with postgres container

I did find a few people with a slightly different setup but with the same issue.我确实发现一些人的设置略有不同但问题相同。 So I hope this doesn't feel like a duplicated question.所以我希望这不会让人觉得是重复的问题。 My setup is pretty simple and straight-forward.我的设置非常简单明了。 I have a container for my node app and a container for my Postgres database.我有一个用于我的节点应用程序的容器和一个用于我的 Postgres 数据库的容器。 When I run docker-compose up and I see the log both containers are up and running.当我运行docker-compose up ,我看到日志中两个容器都已启动并正在运行。 The problem is my node app is not connecting to the database.问题是我的节点应用程序没有连接到数据库。 I can connect to the database using Postbird and it works as it should.我可以使用 Postbird 连接到数据库,它可以正常工作。

If I create a docker container only for the database and run the node app directly on my machine everything works fine.如果我仅为数据库创建一个 docker 容器并直接在我的机器上运行节点应用程序,一切正常。 So it's not and issue with the DB or the app but with the setup.所以这不是数据库或应用程序的问题,而是设置的问题。

Here's a few useful information:以下是一些有用的信息:

Running a docker just for the DB (connects and works perfectly):仅为数据库运行 docker(连接并完美运行):

> vigna-backend@1.0.0 dev /Users/lucasbittar/Dropbox/Code/vigna/backend
> nodemon src/server.js

[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node -r sucrase/register src/server.js`
Initializing database...
Connecting to DB -> vignadb | PORT: 5432
Executing (default): SELECT 1+1 AS result
Connection has been established successfully -> vignadb

Running a container for each using docker-compose:使用 docker-compose 为每个容器运行一个容器:

Creating network "backend_default" with the default driver
Creating backend_db_1 ... done
Creating backend_app_1 ... done
Attaching to backend_db_1, backend_app_1
db_1   |
db_1   | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1   |
db_1   | 2020-07-24 13:23:32.875 UTC [1] LOG:  starting PostgreSQL 12.1 (Debian 12.1-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1   | 2020-07-24 13:23:32.876 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1   | 2020-07-24 13:23:32.876 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1   | 2020-07-24 13:23:32.881 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1   | 2020-07-24 13:23:32.955 UTC [27] LOG:  database system was shut down at 2020-07-23 13:21:09 UTC
db_1   | 2020-07-24 13:23:32.999 UTC [1] LOG:  database system is ready to accept connections
app_1  |
app_1  | > vigna-backend@1.0.0 dev /usr/app
app_1  | > npx sequelize db:migrate && npx sequelize db:seed:all && nodemon src/server.js
app_1  |
app_1  |
app_1  | Sequelize CLI [Node: 14.5.0, CLI: 5.5.1, ORM: 5.21.3]
app_1  |
app_1  | Loaded configuration file "src/config/database.js".
app_1  |
app_1  | Sequelize CLI [Node: 14.5.0, CLI: 5.5.1, ORM: 5.21.3]
app_1  |
app_1  | Loaded configuration file "src/config/database.js".
app_1  | [nodemon] 2.0.2
app_1  | [nodemon] to restart at any time, enter `rs`
app_1  | [nodemon] watching dir(s): *.*
app_1  | [nodemon] watching extensions: js,mjs,json
app_1  | [nodemon] starting `node -r sucrase/register src/server.js`
app_1  | Initializing database...
app_1  | Connecting to DB -> vignadb | PORT: 5432

My database class:我的数据库class:

class Database {
  constructor() {
    console.log('Initializing database...');
    this.init();
  }

  async init() {
    let retries = 5;
    while (retries) {
      console.log(`Connecting to DB -> ${databaseConfig.database} | PORT: ${databaseConfig.port}`);
      const sequelize = new Sequelize(databaseConfig);
      try {
        await sequelize.authenticate();
        console.log(`Connection has been established successfully -> ${databaseConfig.database}`);
        models
          .map(model => model.init(sequelize))
          .map( model => model.associate && model.associate(sequelize.models));
        break;
      } catch (err) {
        console.log(`Error: ${err.message}`);
        retries -= 1;
        console.log(`Retries left: ${retries}`);
        // Wait 5 seconds before trying again
        await new Promise(res => setTimeout(res, 5000));
      }
    }
  }
}

Dockerfile: Dockerfile:

FROM node:alpine

WORKDIR /usr/app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 3333

CMD ["npm", "start"]

docker-compose.yml: docker-compose.yml:

version: "3"

services: 
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_USER: postgres
      POSTGRES_DB: vignadb
    volumes:
      - ./pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"

  app:
    build: .
    depends_on:
      - db
    ports:
      - "3333:3333"
    volumes:
      - .:/usr/app
    command: npm run dev

package.json (scrips only): package.json(仅限纸条):

"scripts": {
  "dev-old": "nodemon src/server.js",
  "dev": "npx sequelize db:migrate && npx sequelize db:seed:all && nodemon src/server.js",
  "build": "sucrase ./src -d ./dist --transforms imports",
  "start": "node dist/server.js"
  },

.env : .env

# Database
DB_HOST=db
DB_USER=postgres
DB_PASS=postgres
DB_NAME=vignadb
DB_PORT=5432

database config:数据库配置:

require('dotenv/config');

module.exports = {
  dialect: 'postgres',
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  port: process.env.DB_PORT,
  define: {
    timestamp: true,
    underscored: true,
    underscoredAll: true,
  },
};

I know I'm messing up something I just don't know where.我知道我搞砸了我只是不知道在哪里的东西。 Let me know if I can provide more information.如果我可以提供更多信息,请告诉我。

Thanks!谢谢!

You should put your 2 containers in the same.network https://docs.docker.com/compose.networking/您应该将 2 个容器放在同一个网络中https://docs.docker.com/compose.networking/

And call your db service inside your nodejs connexion string.并在您的 nodejs 连接字符串中调用您的数据库服务。

Something like: postgres://db:5432/vignadb类似于: postgres://db:5432/vignadb

I did find a few people with a slightly different setup but with the same issue.我确实找到了一些设置略有不同但问题相同的人。 So I hope this doesn't feel like a duplicated question.所以我希望这不会是一个重复的问题。 My setup is pretty simple and straight-forward.我的设置非常简单直接。 I have a container for my node app and a container for my Postgres database.我有一个用于我的节点应用程序的容器和一个用于我的 Postgres 数据库的容器。 When I run docker-compose up and I see the log both containers are up and running.当我运行docker-compose up并看到日志时,两个容器都已启动并正在运行。 The problem is my node app is not connecting to the database.问题是我的节点应用程序没有连接到数据库。 I can connect to the database using Postbird and it works as it should.我可以使用 Postbird 连接到数据库,它可以正常工作。

If I create a docker container only for the database and run the node app directly on my machine everything works fine.如果我仅为数据库创建 docker 容器并直接在我的机器上运行节点应用程序,一切正常。 So it's not and issue with the DB or the app but with the setup.所以这不是数据库或应用程序的问题,而是设置的问题。

Here's a few useful information:这里有一些有用的信息:

Running a docker just for the DB (connects and works perfectly):仅为 DB 运行 docker(连接并完美运行):

> vigna-backend@1.0.0 dev /Users/lucasbittar/Dropbox/Code/vigna/backend
> nodemon src/server.js

[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node -r sucrase/register src/server.js`
Initializing database...
Connecting to DB -> vignadb | PORT: 5432
Executing (default): SELECT 1+1 AS result
Connection has been established successfully -> vignadb

Running a container for each using docker-compose:使用 docker-compose 为每个容器运行一个容器:

Creating network "backend_default" with the default driver
Creating backend_db_1 ... done
Creating backend_app_1 ... done
Attaching to backend_db_1, backend_app_1
db_1   |
db_1   | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1   |
db_1   | 2020-07-24 13:23:32.875 UTC [1] LOG:  starting PostgreSQL 12.1 (Debian 12.1-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1   | 2020-07-24 13:23:32.876 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1   | 2020-07-24 13:23:32.876 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1   | 2020-07-24 13:23:32.881 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1   | 2020-07-24 13:23:32.955 UTC [27] LOG:  database system was shut down at 2020-07-23 13:21:09 UTC
db_1   | 2020-07-24 13:23:32.999 UTC [1] LOG:  database system is ready to accept connections
app_1  |
app_1  | > vigna-backend@1.0.0 dev /usr/app
app_1  | > npx sequelize db:migrate && npx sequelize db:seed:all && nodemon src/server.js
app_1  |
app_1  |
app_1  | Sequelize CLI [Node: 14.5.0, CLI: 5.5.1, ORM: 5.21.3]
app_1  |
app_1  | Loaded configuration file "src/config/database.js".
app_1  |
app_1  | Sequelize CLI [Node: 14.5.0, CLI: 5.5.1, ORM: 5.21.3]
app_1  |
app_1  | Loaded configuration file "src/config/database.js".
app_1  | [nodemon] 2.0.2
app_1  | [nodemon] to restart at any time, enter `rs`
app_1  | [nodemon] watching dir(s): *.*
app_1  | [nodemon] watching extensions: js,mjs,json
app_1  | [nodemon] starting `node -r sucrase/register src/server.js`
app_1  | Initializing database...
app_1  | Connecting to DB -> vignadb | PORT: 5432

My database class:我的数据库 class:

class Database {
  constructor() {
    console.log('Initializing database...');
    this.init();
  }

  async init() {
    let retries = 5;
    while (retries) {
      console.log(`Connecting to DB -> ${databaseConfig.database} | PORT: ${databaseConfig.port}`);
      const sequelize = new Sequelize(databaseConfig);
      try {
        await sequelize.authenticate();
        console.log(`Connection has been established successfully -> ${databaseConfig.database}`);
        models
          .map(model => model.init(sequelize))
          .map( model => model.associate && model.associate(sequelize.models));
        break;
      } catch (err) {
        console.log(`Error: ${err.message}`);
        retries -= 1;
        console.log(`Retries left: ${retries}`);
        // Wait 5 seconds before trying again
        await new Promise(res => setTimeout(res, 5000));
      }
    }
  }
}

Dockerfile: Dockerfile:

FROM node:alpine

WORKDIR /usr/app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 3333

CMD ["npm", "start"]

docker-compose.yml: docker-compose.yml:

version: "3"

services: 
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_USER: postgres
      POSTGRES_DB: vignadb
    volumes:
      - ./pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"

  app:
    build: .
    depends_on:
      - db
    ports:
      - "3333:3333"
    volumes:
      - .:/usr/app
    command: npm run dev

package.json (scrips only): package.json(仅脚本):

"scripts": {
  "dev-old": "nodemon src/server.js",
  "dev": "npx sequelize db:migrate && npx sequelize db:seed:all && nodemon src/server.js",
  "build": "sucrase ./src -d ./dist --transforms imports",
  "start": "node dist/server.js"
  },

.env : .env

# Database
DB_HOST=db
DB_USER=postgres
DB_PASS=postgres
DB_NAME=vignadb
DB_PORT=5432

database config:数据库配置:

require('dotenv/config');

module.exports = {
  dialect: 'postgres',
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  port: process.env.DB_PORT,
  define: {
    timestamp: true,
    underscored: true,
    underscoredAll: true,
  },
};

I know I'm messing up something I just don't know where.我知道我搞砸了一些我只是不知道在哪里。 Let me know if I can provide more information.让我知道我是否可以提供更多信息。

Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM