Ask Your Question
4

What are the steps required to enable a Next.js application to utilize Postgres with docker-compose?

asked 2023-04-05 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-01-12 00:00:00 +0000

nofretete gravatar image

The steps required to enable a Next.js application to utilize Postgres with docker-compose are:

  1. Install Docker and Docker-compose on your machine if you haven't already.

  2. Create a new folder named db in the root directory of your Next.js project.

  3. Create a new file named docker-compose.yaml in the db folder.

  4. Add the following code to the docker-compose.yaml file:

version: '3'

services:
  db:
    image: postgres
    volumes:
      - ./data:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: <username>
      POSTGRES_PASSWORD: <password>
      POSTGRES_DB: <database-name>
    ports:
      - "5432:5432"

Replace <username>, <password>, and <database-name> with your desired values. This code will create a postgres database container and expose it on port 5432.

  1. Create a new folder named data in the db folder.

  2. Run the following command to start the postgres container:

docker-compose up -d

This will start the database container in the background. You can verify that it's running by running the following command:

docker-compose ps
  1. Install the pg package in your Next.js application by running the following command:
npm install pg
  1. Create a new file named db.js in the root directory of your Next.js project.

  2. Add the following code to the db.js file:

import { Pool } from 'pg';

const pool = new Pool({
  user: <username>,
  password: <password>,
  host: 'localhost',
  port: 5432,
  database: <database-name>,
});

export default {
  query: (text, params) => pool.query(text, params),
};

Make sure to replace <username>, <password>, and <database-name> with your values from step 4.

  1. You can now use the query method from the db.js file to run SQL queries against your Postgres database.

An example usage of the query method:

import db from './db';

async function getUsers() {
  const { rows } = await db.query('SELECT * FROM users');
  return rows;
}

This will return an array of all the users in the users table.

That's it! Your Next.js application is now utilizing Postgres via docker-compose.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-05 11:00:00 +0000

Seen: 10 times

Last updated: Jan 12 '22