The steps required to enable a Next.js application to utilize Postgres with docker-compose are:
Install Docker and Docker-compose on your machine if you haven't already.
Create a new folder named db
in the root directory of your Next.js project.
Create a new file named docker-compose.yaml
in the db
folder.
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.
Create a new folder named data
in the db
folder.
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
pg
package in your Next.js application by running the following command:npm install pg
Create a new file named db.js
in the root directory of your Next.js project.
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.
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.
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
Asked: 2023-04-05 11:00:00 +0000
Seen: 10 times
Last updated: Jan 12 '22
How can the SQL debug mode be activated in PostgreSQL version 15.2?
What is the procedure for using pg_restore on Windows with Docker?
What is the equivalent of SQL Server NVARCHAR in PostgreSQL?
What is the method to retrieve the JSON data from a column in SQL?
How to solve the issue of being unable to establish a connection with libpq on Mac M1?
Is it possible to launch multiple instances of PostgreSQL using Spring Boot Testcontainers?
Due to SyntaxError, why am I unable to create a TIMESTAMP WITH TIMEZONE column in postgres?