How to use PostgreSQL in Docker with Docker Compose and Node.js

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.

  1. Create a project directory:
  2. mkdir node-postgres-docker
    cd node-postgres-docker
  3. Create a docker-compose.yml file in the directory and add the following content:
  4. 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:
  5. Start PostgreSQL:
  6. docker-compose up -d
  7. Check that the container is running:
  8. docker ps

Step 2: Configure Node.js

  1. Start by creating a Node.js application:
  2. mkdir app
    cd app
    npm init -y
  3. Install the necessary dependencies:
  4. npm install pg dotenv
  5. Create a .env file to store configuration variables:
  6. DB_HOST=localhost
    DB_PORT=5432
    DB_USER=user
    DB_PASSWORD=password
    DB_NAME=mydatabase
  7. Create an index.js file in the app directory with the following content:
  8. 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();
  9. Run the application to test the connection:
  10. 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:

  1. Modify index.js to create a table:
  2. 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();
  3. Run the application again:
  4. 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.

Back to top