docker-compose: nodejs container not communicating with postgres container

蹲街弑〆低调 提交于 2021-02-10 15:39:06

问题


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. When I run docker-compose up and I see the log both containers are up and running. 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.

If I create a docker container only for the database and run the node app directly on my machine everything works fine. 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):

> 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:

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 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:

FROM node:alpine

WORKDIR /usr/app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 3333

CMD ["npm", "start"]

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):

"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:

# 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!


回答1:


You should put your 2 containers in the same network https://docs.docker.com/compose/networking/

And call your db service inside your nodejs connexion string.

Something like: postgres://db:5432/vignadb




回答2:


Bro, It's not sequelize but sequelize-cli in your package.json.

Try this and tell me what's happen.



来源:https://stackoverflow.com/questions/63074581/docker-compose-nodejs-container-not-communicating-with-postgres-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!