Docker simplifies managing databases like PostgreSQL, making it easy to set up an isolated and reproducible environment. In this article, we’ll see how to set up PostgreSQL in Docker using Docker Compose and integrate it with a Node.js application.
Prerequisites
- Docker and Docker Compose installed on your machine.
- Node.js installed (LTS version recommended).
Step 1: Configure Docker Compose for PostgreSQL
Start by creating a docker-compose.yml
file to configure a PostgreSQL service.
- Create a project directory:
- Create a
docker-compose.yml
file in the directory and add the following content: - Start PostgreSQL:
- Check that the container is running:
mkdir node-postgres-docker
cd node-postgres-docker
version: '3.8'
services:
postgres:
image: postgres:15
container_name: postgres_container
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydatabase
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
docker-compose up -d
docker ps
Step 2: Configure Node.js
- Start by creating a Node.js application:
- Install the necessary dependencies:
- Create a
.env
file to store configuration variables: - Create an
index.js
file in theapp
directory with the following content: - Run the application to test the connection:
mkdir app
cd app
npm init -y
npm install pg dotenv
DB_HOST=localhost
DB_PORT=5432
DB_USER=user
DB_PASSWORD=password
DB_NAME=mydatabase
const { Pool } = require('pg');
require('dotenv').config();
const pool = new Pool({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
async function testConnection() {
try {
const client = await pool.connect();
console.log('Connected to the database!');
const result = await client.query('SELECT NOW() AS current_time');
console.log(result.rows[0]);
client.release();
} catch (err) {
console.error('Connection error:', err);
} finally {
pool.end();
}
}
testConnection();
node index.js
Step 3: Data Persistence
In the docker-compose.yml
file, we configured a postgres_data
volume to ensure data persists even if the container is removed. You can verify the data is stored in:
/var/lib/docker/volumes
Step 4: Interacting with the Database
You can create tables, execute queries, and interact with the database using the pg
module. Example:
- Modify
index.js
to create a table: - Run the application again:
async function createTable() {
try {
const client = await pool.connect();
await client.query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
`);
console.log('Table created successfully!');
client.release();
} catch (err) {
console.error('Error creating table:', err);
}
}
createTable();
node index.js
Step 5: Debugging and Troubleshooting
- Database connection error: Check that the PostgreSQL container is running and credentials are correct.
- Network issues: Ensure port 5432 is not being used by another process.
- Environment variables: Verify that the
.env
file is correctly configured and loaded by the Node.js app.
Conclusion
Using Docker Compose for PostgreSQL simplifies setting up and managing a database for Node.js applications. With just a few commands, you can have a ready-to-use environment for development or production. By following these steps, you have everything you need to start building scalable and well-structured applications with Node.js and PostgreSQL.