Containers and Kubernetes · Intermediate · 16 min
How to Run an App and PostgreSQL Together with Docker Compose
By Padding · Updated 15 Nov 2026
Docker Compose 5.7 · PostgreSQL 18
You will describe a Node.js app and a PostgreSQL 18 database in one compose.yaml, start both with one command, keep the data in a named volume, and keep the database password out of the file.
On this page
An app on its own is rarely the whole system. It needs a database, and starting each piece with a long docker run command, in the right order, with the right network and passwords, does not scale past two containers. Docker Compose lets you write the whole arrangement down in one file and bring it up or down with a single command.
In this tutorial you will build a small web app that counts its own page views in PostgreSQL 18. You will write the compose.yaml, make the app wait until the database is ready, check that the data survives a restart, and remove everything at the end. It is the third tutorial in the series From Docker to Kubernetes. If you have not written a Dockerfile before, read /tutorials/write-a-dockerfile-for-a-node-app first.
Step 1 · Check Compose and create the app
Confirm that the Compose plugin is installed. It ships with Docker Engine when you install it from Docker's own apt repository, as in /tutorials/install-docker-engine-on-ubuntu-26-04:
docker compose versionThe output starts with Docker Compose version v5.. Note that the command is docker compose with a space. The older docker-compose with a hyphen was a separate Python program and is no longer maintained.
Create a project folder, and add the web framework and the PostgreSQL client for Node.js:
mkdir hits-app
cd hits-app
npm init -y
npm install express pgWrite the app. On start it creates a hits table if there is none. Each request to / adds one row and returns the total. The connection string comes from the DATABASE_URL environment variable, so no password appears in the code:
cat > server.js <<'JS'
const express = require('express')
const { Pool } = require('pg')
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
const app = express()
app.get('/', async (req, res) => {
await pool.query('INSERT INTO hits DEFAULT VALUES')
const { rows } = await pool.query('SELECT count(*)::int AS total FROM hits')
res.json({ hits: rows[0].total })
})
async function main() {
await pool.query(
'CREATE TABLE IF NOT EXISTS hits (id serial PRIMARY KEY, at timestamptz NOT NULL DEFAULT now())'
)
const server = app.listen(3000, () => console.log('Listening on port 3000'))
process.on('SIGTERM', () => {
server.close(() => pool.end().then(() => process.exit(0)))
})
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
JSAdd a Dockerfile and a .dockerignore. They follow the previous tutorial, so read that one for the reasoning behind each line:
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY server.js ./
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]
DOCKER
cat > .dockerignore <<'IGNORE'
node_modules
.git
.env
.env.*
IGNOREStep 2 · Keep the password in a private file
Compose reads a file named .env in the project folder and uses its values wherever the compose file refers to a variable. That keeps the database password out of compose.yaml, which you will commit to Git. Create the file private first, then write into it, so it is never readable by other users. The password comes from a random generator, not from your keyboard:
install -m 600 /dev/null .env
echo "POSTGRES_PASSWORD=$(openssl rand -hex 16)" >> .env
ls -l .envThe listing shows mode -rw-------. Do not print the file into a shared terminal or a chat. Add .env to your .gitignore if the folder is a Git repository, as covered in /tutorials/keep-secrets-out-of-git.
Step 3 · Write compose.yaml
Create compose.yaml in the project folder. A top-level version: key is no longer needed; current Compose ignores it and prints a warning if it is there.
cat > compose.yaml <<'YAML'
name: hits-app
services:
db:
image: postgres:18
restart: unless-stopped
environment:
POSTGRES_USER: app
POSTGRES_DB: appdb
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
volumes:
- dbdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 3s
timeout: 3s
retries: 10
start_period: 20s
web:
build: .
restart: unless-stopped
environment:
DATABASE_URL: postgres://app:${POSTGRES_PASSWORD}@db:5432/appdb
ports:
- "127.0.0.1:3000:3000"
depends_on:
db:
condition: service_healthy
volumes:
dbdata:
YAMLWhat each part does:
name: hits-appsets the project name. Compose uses it as a prefix for the containers, the network and the volume, such ashits-app-db-1andhits-app_dbdata.servicesholds one entry per container. Compose puts them all on one private network and lets each reach the others by service name. That is why the app connects to the hostdb, not to an IP address.image: postgres:18is the official PostgreSQL image. ThePOSTGRES_*variables are read by the image the first time it starts on an empty data folder.${POSTGRES_PASSWORD:?...}takes the value from.envand stops with the message if it is missing.dbdata:/var/lib/postgresqlmounts a named volume, which Docker manages and which outlives the container. For PostgreSQL 18 and later, the image keeps its data in a version-numbered folder below/var/lib/postgresql, so you mount that parent folder. Guides written for older images mount/var/lib/postgresql/data, which does not work the same way on 18.healthcheckrunspg_isreadyinside the database container every three seconds. It asks over TCP (-h 127.0.0.1) on purpose: on its first start, the image runs a temporary server that listens only on a local socket while it creates the database, and a check without-hwould report healthy during that setup, too early for the app.start_periodgives the first start 20 seconds before failed checks count. The doubled$$stops Compose from replacing the variable itself, so the container's shell does it.depends_onwithcondition: service_healthymakes Compose startwebonly after the database reports healthy. Plaindepends_ononly waits for the container to start, which is much earlier than the moment PostgreSQL accepts connections.127.0.0.1:3000:3000publishes the app on your machine only. The database has noportsentry on purpose: only the app, on the private network, can reach it.
Ask Compose to read the file and print the result with every variable filled in. This catches indentation mistakes before anything starts:
docker compose config --quiet && echo "compose.yaml is valid"Note that plain docker compose config prints the password too, so do not paste its output anywhere.
Step 4 · Start the stack
Build the app image, create the network and volume, and start both containers in the background. --wait makes the command return only when the services are running and healthy:
docker compose up -d --build --waitThe first run pulls postgres:18 and builds the app image, so it takes a minute or two. The output ends with lines such as Container hits-app-db-1 Healthy and Container hits-app-web-1 Started.
Check it worked
docker compose ps
curl -s http://localhost:3000/
curl -s http://localhost:3000/docker compose ps lists both services as running, and db as healthy. The two requests print {"hits":1} and {"hits":2}. The counter lives in the database, not in the app. Look inside it:
docker compose exec db psql -U app -d appdb -c 'SELECT count(*) FROM hits;'The count is 2. docker compose exec runs a command in a running service, and the psql client is inside the database image.
Troubleshooting
Bind for 127.0.0.1:3000 failed: port is already allocated: another program or container uses port 3000. Stop it, or change the left number inports, for example"127.0.0.1:3001:3000".required variable POSTGRES_PASSWORD is missing a value: you are not in the project folder, or.envis empty. Compose reads.envfrom the folder where you run the command.password authentication failed for user "app"after you changed the password in.env: PostgreSQL only readsPOSTGRES_PASSWORDwhen it creates an empty data folder. The volume already holds the old password. Either change the password inside PostgreSQL withALTER USER, or remove the volume (the last step shows how, and it deletes the data).- The app keeps restarting: run
docker compose logs web. A stack trace about a connection or a missing table points atDATABASE_URLor the database container; read the lines above it.
Step 5 · Read the logs and change the app
Logs from both services, merged and prefixed with the service name:
docker compose logs --tail 5Follow them live with docker compose logs -f and stop with Ctrl+C. To change the app, edit server.js and rebuild only that service. Compose recreates just the containers whose image or settings changed, and leaves the database alone:
sed -i.bak 's/{ hits: rows\[0\].total }/{ hits: rows[0].total, service: "web" }/' server.js
rm server.js.bak
docker compose up -d --build --wait web
curl -s http://localhost:3000/The reply now has "service":"web" and a hit count of 3, so the database kept the earlier rows while the app container was replaced.
Step 6 · Prove the data survives
docker compose down stops and removes the containers and the network. It does not remove named volumes unless you add -v:
docker compose down
docker volume ls --filter name=hits-appThe volume hits-app_dbdata is still listed. Start the stack again and request the page:
docker compose up -d --wait
curl -s http://localhost:3000/The count continues at 4 with the earlier rows intact. The containers are new, but PostgreSQL found its data in the volume. To keep this data safe on a real system, also take backups; see /tutorials/back-up-and-restore-postgresql-with-pg-dump.
Step 7 · Clean up
The next command deletes the stack, the network and, because of -v, the volume with all the data in it. --rmi local also removes the image Compose built for the app. Run it only when you no longer need the data:
docker compose down -v --rmi localThen check that nothing is left:
docker ps -a --filter name=hits-app
docker volume ls --filter name=hits-appBoth lists are empty. The postgres:18 image stays on your machine for next time. Remove it with docker rmi postgres:18 if you want the space back.
Next steps
- Understand what the file leaves out and what to add for production: backups, resource limits, and a reverse proxy in front of the app, as in
/tutorials/nginx-reverse-proxy-for-a-node-app. - Shrink the app image with
/tutorials/make-docker-images-smaller-multi-stage. - Run the same app on Kubernetes, starting with
/tutorials/run-your-first-kubernetes-cluster-with-kind. - The file reference is at docs.docker.com/reference/compose-file/.
Related tutorials
- How to Write a Dockerfile for a Node.js AppYou will write a Dockerfile for a small Express app on Node.js 26, build it into an image, run it as a container on port 3000 as a non-root user, and order the file so rebuilds take seconds.
- How to Install Docker Engine on Ubuntu 26.04You will install Docker Engine 29 from Docker's official apt repository on Ubuntu 26.04, run the hello-world image to prove it works, and set it up to start at boot, run without sudo and keep its logs from filling the disk.
- How to Keep Passwords and API Keys Out of GitYou will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials