Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect a node docker container with postgres docker container

I have a CRUD app working on node, on my local machine. It is running on node, with postgres as the database, using knex.js as a query builder, etc.

I have created a docker file, and a docker-compose file, and the containers start, but the node container can't reach the postgres container. I suspect it has to do with the enviornment variables but I am not sure. here is my docker file:

FROM node:12
# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm ci --only=production

# Bundle app source
COPY . .

ENV PORT=8080
EXPOSE 8080

CMD [ "npm", "start" ]

This is the docker-compose file:

version: '2'
services:
  postgres:
    image: postgres:alpine
    environment:
      POSTGRES_PASSWORD: password
      POSTGRES_USER: app
      POSTGRES_DB: db

  app:
    build: .
    depends_on:
      - "postgres"
    links:
      - "postgres"
    environment:
      DB_PASSWORD: 'password'
      DB_USER: 'app'
      DB_NAME: 'db'
      DB_HOST: 'postgres'
      PORT: 8080
    ports:
      - '8080:8080'
    command: npm start

also, here is the knex.js file on root that handles the db connections based on the environment:

// Update with your config settings.

module.exports = {

  development: {
    client: 'pg',
    connection: 'postgres://localhost/db'
  },
  test: {
    client: 'pg',
    connection: 'postgres://localhost/test-db'
  }
};

additionally when I check the hosts file on the node app inside the docker i don't see anything mentioning the link to postgres container. Any help would be appreciated, thanks.

like image 440
jdix87 Avatar asked Aug 05 '26 09:08

jdix87


1 Answers

The reason why your node application is not connecting is because it is trying to connect to itself as you are referencing localhost. Your database is in a second container which is not local so you need to reference it by service name which would be postgres.

So assuming your application is handling authentication another way, your config would be something like this:

// Update with your config settings.

module.exports = {

  development: {
    client: 'pg',
    connection: 'postgres://postgres/db'
  },
  test: {
    client: 'pg',
    connection: 'postgres://postgres/test-db'
  }
};

If you can, you should use the environment variables you assigned to the app container.

like image 157
leeman24 Avatar answered Aug 07 '26 00:08

leeman24



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!