โUpdate my Node.js app to read DB_HOST, DB_PORT, DB_USER and DB_PASSWORD from process.env and connect to Postgres. Never hardcode credentials.โ
09 โ Wire app to Postgres using environment variables
Category: Docker Compose ยท Priority: High ยท Step: 10
Use
DB_HOST=db(the service name),DB_PORT=5432. Never hardcode credentials โ read them from the.envfile.
๐ฏ What is this task?
Now you'll update your app so it actually reads from the Postgres database using environment variables. The key rule: never hardcode database credentials in your code. Always read them from process.env. This is how every real production app works.
๐ค AI Prompt
"Update my Node.js Express app (
index.js) to connect to Postgres using thepgnpm package. Read all connection details from environment variables:DB_HOST,DB_PORT,DB_NAME,DB_USER,DB_PASSWORD. Add a new routeGET /db-testthat runs a simple querySELECT NOW()and returns the result as JSON. Handle connection errors gracefully. Show the full updatedindex.jsand the updatedpackage.json."
๐ Step-by-step
Step 1 โ Install the Postgres client library
npm install pg
This adds pg to your package.json dependencies.
Step 2 โ Update index.js
const express = require('express');
const { Pool } = require('pg');
const app = express();
const PORT = process.env.PORT || 3000;
// Database connection โ reads from environment variables
const pool = new Pool({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
});
app.get('/', (req, res) => {
res.json({ message: 'Hello from Docker!' });
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// New route to test DB connection
app.get('/db-test', async (req, res) => {
try {
const result = await pool.query('SELECT NOW() as current_time');
res.json({
status: 'connected',
db_time: result.rows[0].current_time
});
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 3 โ Rebuild and restart
Because you added a new npm package, you need to rebuild the Docker image:
docker compose down
docker compose up --build
The --build flag forces Docker to rebuild the image with the new pg dependency.
Step 4 โ Test the database connection
Open http://localhost:3000/db-test in your browser. You should see something like:
{
"status": "connected",
"db_time": "2026-03-09T12:00:00.000Z"
}
If you see an error, check docker compose logs app to see what went wrong.
โ Done when
-
pgis inpackage.jsondependencies -
index.jsreads DB credentials fromprocess.env -
http://localhost:3000/db-testreturns{ "status": "connected" } - No credentials are hardcoded in the source code
๐ Quiz
Answer all 2 questions correctly to complete this lesson.