How to Deploy a Multi-Container App with Docker Compose on Ubuntu 24.04

Serdar Tekin
Serdar Tekin
Co-Founder & CTO
IntermediateUpdated 19 min read~45+ minutes total
Docker ComposeUbuntu 24.04DockerPostgreSQLRedisNode.jsContainers
Last reviewed:
Tutorial
How to Deploy a Multi-Container App with Docker Compose on Ubuntu 24.04
rafftechnologies.com/learn

Prerequisites

  • A Raff Linux VM running Ubuntu 24.04, SSH access with a non-root sudo user, Docker Engine installed from the official Docker repository, and the Docker Compose plugin

Run your Node.js, PostgreSQL and Redis stack on one Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

  1. 1Pick a Linux imageUbuntu, Debian and more, with your SSH key added.
  2. 2Choose a sizeFrom $4.99 a month. Resize when your app grows.
  3. 3Connect over SSHYour server is up in about 55 seconds.

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

Docker Compose lets you define a multi-container application in one compose.yaml file and manage the stack with commands such as docker compose up, docker compose ps, and docker compose down. In this tutorial, you will deploy a small Node.js API with PostgreSQL and Redis on a Raff Linux VM running Ubuntu 24.04. The database and cache stay on the internal Compose network, PostgreSQL uses a named volume for persistent data, the database password is mounted as a Compose secret instead of being hardcoded in YAML, and the application port is bound to localhost rather than exposed directly to the internet.

This tutorial focuses on a single-host Docker Compose deployment. Docker's current documentation supports health-check-aware startup ordering through depends_on with condition: service_healthy, named volumes for persistent state, and the Compose plugin through the docker compose command. Docker also recommends using secrets rather than ordinary environment variables for sensitive values. See the Docker Compose plugin installation guide, startup-order documentation, and environment-variable guidance for the upstream behavior used here.

For deployment design and operational trade-offs, read Docker Compose for Production.

You need Ubuntu 24.04, Docker Engine with the Compose plugin, a non-root SSH account with sudo privileges, and enough capacity for the application, PostgreSQL, and Redis you intend to run. Use the same non-root account for every project command below.

Step 1 — Verify Docker Engine and the Compose Plugin

Confirm Docker and Compose are installed:

Bash
docker --version docker compose version

If docker compose is missing but Docker Engine is already installed from Docker's official repository, install the plugin:

Bash
sudo apt update sudo apt install -y docker-compose-plugin

Docker's current Linux documentation treats docker compose as the supported plugin command. The old standalone docker-compose installation is retained only for backward compatibility.

If Docker Engine itself is not installed, follow How to Install Docker on Ubuntu 24.04 instead of mixing package sources.

Install the host utilities used below:

Bash
sudo apt update sudo apt install -y curl openssl

Verify: docker info completes successfully, docker compose version reports the Compose plugin, and curl --version and openssl version report installed utilities.

Step 2 — Create the Project and Secret Directories

Create a project directory:

Bash
mkdir -p ~/task-api/src ~/task-api/secrets cd ~/task-api

Check the numeric identity of your project account:

Bash
id -u id -g

The user ID must be non-zero. If id -u prints 0, reconnect as your non-root sudo user before continuing.

Record that user's IDs for the application container:

Bash
printf 'TASK_API_UID=%s\nTASK_API_GID=%s\n' \ "$(id -u)" "$(id -g)" > .env

Generate a random PostgreSQL password without overwriting a secret already used by the database:

Bash
if [ ! -s secrets/postgres_password ]; then ( umask 077 openssl rand -hex 32 > secrets/postgres_password ) fi chmod 600 secrets/postgres_password

Docker Compose file-based secrets use bind mounts. Their filesystem ownership still matters: Step 5 runs the app with the same non-root UID and GID as the secret's owner, while the file stays mode 600. Regenerating this file after PostgreSQL initialization does not rotate the existing database password.

Prevent local secret material from being committed to Git:

Bash
cat > .gitignore <<'EOF' secrets/ .env EOF

Do not paste the generated password into compose.yaml, shell history, screenshots, or support tickets.

Verify: cat .env shows the non-zero user ID and group ID from id. stat -c '%a %u:%g %n' secrets/postgres_password shows mode 600 and the same owner IDs. test -s secrets/postgres_password && echo secret-created confirms a non-empty secret without printing it.

Step 3 — Create the Node.js API

Create the application package file:

Bash
cat > src/package.json <<'EOF' { "name": "compose-task-api", "version": "1.0.0", "private": true, "main": "index.js", "dependencies": { "express": "^4.21.0", "pg": "^8.13.0", "redis": "^4.7.0" } } EOF

Create the API:

Bash
cat > src/index.js <<'EOF' const fs = require('fs'); const express = require('express'); const { Pool } = require('pg'); const { createClient } = require('redis'); const app = express(); app.use(express.json()); const dbPassword = fs.readFileSync( process.env.POSTGRES_PASSWORD_FILE || '/run/secrets/postgres_password', 'utf8' ).trim(); const pool = new Pool({ host: process.env.POSTGRES_HOST || 'db', port: 5432, user: process.env.POSTGRES_USER || 'taskuser', password: dbPassword, database: process.env.POSTGRES_DB || 'taskdb' }); const redis = createClient({ url: `redis://${process.env.REDIS_HOST || 'cache'}:6379` }); redis.on('error', (err) => console.error('Redis error:', err.message)); app.get('/health', async (req, res) => { try { await pool.query('SELECT 1'); await redis.ping(); res.json({ status: 'ok' }); } catch (err) { res.status(503).json({ status: 'error' }); } }); app.get('/tasks', async (req, res) => { const cached = await redis.get('tasks'); if (cached) return res.json(JSON.parse(cached)); const { rows } = await pool.query( 'SELECT id, title, done, created_at FROM tasks ORDER BY id DESC' ); await redis.setEx('tasks', 30, JSON.stringify(rows)); res.json(rows); }); app.post('/tasks', async (req, res) => { const title = String(req.body.title || '').trim(); if (!title || title.length > 255) { return res.status(400).json({ error: 'title must contain 1-255 characters' }); } const { rows } = await pool.query( 'INSERT INTO tasks (title) VALUES ($1) RETURNING id, title, done, created_at', [title] ); await redis.del('tasks'); res.status(201).json(rows[0]); }); async function start() { await redis.connect(); await pool.query(` CREATE TABLE IF NOT EXISTS tasks ( id SERIAL PRIMARY KEY, title VARCHAR(255) NOT NULL, done BOOLEAN NOT NULL DEFAULT false, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ) `); app.listen(3000, '0.0.0.0', () => { console.log('Task API listening on port 3000'); }); } start().catch((err) => { console.error(err); process.exit(1); }); EOF

The API verifies both PostgreSQL and Redis on /health, uses parameterized SQL for task creation, and reads the database password from a mounted secret file.

Verify: Run node --check src/index.js if Node.js is installed on the host. If it is not, continue to the container build and use the container logs as the syntax/runtime check.

Step 4 — Create the Application Dockerfile

Create src/Dockerfile:

Bash
cat > src/Dockerfile <<'EOF' FROM node:22-slim WORKDIR /app COPY --chmod=0644 package.json ./ RUN npm install --omit=dev && npm cache clean --force COPY --chmod=0644 index.js ./ EXPOSE 3000 USER node CMD ["node", "index.js"] EOF

The image defaults to the non-root node user. In Step 5, Compose overrides that identity with the project owner's non-root UID and GID so the app can read its mode-600 secret. The copied application files are readable without granting write access, and npm installs dependencies during the image build. The Dockerfile does not copy your project-level secrets/ directory into the image.

Create a Docker build ignore file:

Bash
cat > src/.dockerignore <<'EOF' node_modules npm-debug.log EOF

Verify: Run docker build -t task-api-check ./src. The image build should finish successfully without copying secret files into the build context.

Step 5 — Define the Multi-Container Compose Stack

Create compose.yaml:

Bash
cat > compose.yaml <<'EOF' services: app: build: ./src user: "${TASK_API_UID:?Set TASK_API_UID in .env}:${TASK_API_GID:?Set TASK_API_GID in .env}" restart: unless-stopped environment: POSTGRES_HOST: db POSTGRES_USER: taskuser POSTGRES_DB: taskdb POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password REDIS_HOST: cache secrets: - postgres_password ports: - "127.0.0.1:3000:3000" depends_on: db: condition: service_healthy restart: true cache: condition: service_healthy restart: true networks: - backend db: image: postgres:16-alpine restart: unless-stopped environment: POSTGRES_USER: taskuser POSTGRES_DB: taskdb POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password secrets: - postgres_password volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U taskuser -d taskdb"] interval: 10s timeout: 5s retries: 5 start_period: 20s networks: - backend cache: image: redis:7-alpine restart: unless-stopped command: ["redis-server", "--appendonly", "yes"] volumes: - redisdata:/data healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 5s retries: 5 start_period: 10s networks: - backend secrets: postgres_password: file: ./secrets/postgres_password volumes: pgdata: redisdata: networks: backend: driver: bridge EOF

The database and Redis services have no ports section, so they are not published on the host. The API is published only on 127.0.0.1:3000. Docker Compose waits for the PostgreSQL and Redis health checks because both dependencies use condition: service_healthy.

The app's user value comes from the project .env file and must match the secret-file owner from Step 2. Keep the database service's user unchanged: the official PostgreSQL entrypoint reads POSTGRES_PASSWORD_FILE during initialization before it switches to the database account.

Verify: Run docker compose config -q and docker compose config --services. Validation should pass and the service list should contain app, db, and cache.

Step 6 — Start the Stack and Wait for Healthy Dependencies

Build and start the application:

Bash
cd ~/task-api docker compose up -d --build

Check the containers:

Bash
docker compose ps

Review the application logs:

Bash
docker compose logs --tail=100 app

Verify the running application's identity and secret access without displaying the password:

Bash
docker compose exec -T app sh -c \ 'id && test -r /run/secrets/postgres_password && echo secret-readable'

The IDs must match Step 2, and secret-readable confirms access. If the app cannot start, inspect its logs and compare the IDs in .env with the secret-file owner before changing permissions.

Compose starts dependencies in order, but simple startup ordering alone does not mean a database is ready to accept connections. The health checks in this tutorial provide the readiness condition before the app is started.

Verify: PostgreSQL and Redis should report healthy status, the app should be running, and the app log should contain Task API listening on port 3000 without a repeating database or Redis connection error.

Step 7 — Test the Application End to End

Check the health endpoint from the VM:

Bash
curl -fsS http://127.0.0.1:3000/health

Expected result:

Json
{"status":"ok"}

Create a task:

Bash
curl -fsS -X POST http://127.0.0.1:3000/tasks \ -H 'Content-Type: application/json' \ -d '{"title":"Deploy with Docker Compose"}'

Retrieve tasks:

Bash
curl -fsS http://127.0.0.1:3000/tasks

The request path now exercises the application container, PostgreSQL service, Redis service, Compose network, secret mount, and database volume together.

Verify: /health should return status: ok, the POST should return the created task, and the GET should return that task.

Step 8 — Confirm Internal Services Are Not Published Publicly

List listening host ports:

Bash
sudo ss -lntp | grep -E ':(3000|5432|6379)\b' || true

Only the API's localhost mapping should appear:

Text
127.0.0.1:3000

PostgreSQL port 5432 and Redis port 6379 should not be listening on the host merely because the containers use those ports internally.

Inspect Compose port mappings:

Bash
docker compose ps

For a public application, place Nginx or Caddy in front of 127.0.0.1:3000 and terminate HTTPS there instead of changing the API mapping to 0.0.0.0:3000. See How to Install Caddy on Ubuntu 24.04 as a Reverse Proxy or How to Secure Nginx with Let's Encrypt.

Verify: The host should not expose 5432 or 6379, and port 3000 should remain bound to 127.0.0.1.

Step 9 — Inspect Logs, Health, and Resource Usage

Check service state:

Bash
docker compose ps

View recent logs without following indefinitely:

Bash
docker compose logs --tail=100 app docker compose logs --tail=100 db docker compose logs --tail=100 cache

View a current resource snapshot:

Bash
docker compose stats --no-stream

Treat the output as a measurement of your current workload, not as a universal sizing rule. CPU and memory use vary with image versions, database state, traffic, query patterns, and application behavior.

Verify: Services should remain running, PostgreSQL and Redis should remain healthy, and logs should not show unresolved repeating errors.

Step 10 — Verify Named-Volume Persistence

Create another task:

Bash
curl -fsS -X POST http://127.0.0.1:3000/tasks \ -H 'Content-Type: application/json' \ -d '{"title":"Persistence test"}'

Remove the containers and Compose network without deleting volumes:

Bash
docker compose down

Confirm the project volumes still exist:

Bash
docker volume ls | grep -E 'pgdata|redisdata'

Recreate the stack:

Bash
docker compose up -d

Wait for the health checks, then query the API:

Bash
curl -fsS http://127.0.0.1:3000/tasks

A normal docker compose down does not delete named volumes. docker compose down -v does.

Verify: The Persistence test task should still exist after the containers are recreated.

Step 11 — Back Up PostgreSQL Before Updates or Destructive Changes

Create a protected backup directory:

Bash
mkdir -p ~/task-api/backups chmod 700 ~/task-api/backups

Create a PostgreSQL dump:

Bash
cd ~/task-api docker compose exec -T db \ pg_dump -U taskuser -d taskdb \ > "backups/taskdb-$(date +%F-%H%M%S).sql"

Check that the file exists and is non-empty:

Bash
ls -lh backups/ test -s "$(ls -1t backups/taskdb-*.sql | head -n 1)" && echo 'Database dump is non-empty'

A backup stored only on the same VM is not a complete disaster-recovery plan. Copy production backups to separate protected storage and test restore procedures before relying on them.

Verify: A timestamped, non-empty SQL dump should exist before you perform an update or any command that may delete data.

Step 12 — Update the Stack with a Controlled Recreate

Before changing image tags or application code, create a fresh backup and review the relevant release notes.

Pull service images:

Bash
docker compose pull db cache

Rebuild the application image and recreate changed services:

Bash
docker compose up -d --build

Check state and logs:

Bash
docker compose ps docker compose logs --tail=100 app

Do not upgrade PostgreSQL to a new major version by simply changing postgres:16-alpine to another major tag while reusing the same data directory. PostgreSQL major-version upgrades require an appropriate upgrade or dump-and-restore procedure.

Verify: The expected containers should be running after the recreate, the dependencies should be healthy, and /health should return status: ok.

Step 13 — Troubleshoot Common Docker Compose Failures

If Compose rejects the YAML, validate it:

Bash
docker compose config -q

If the application exits, inspect its logs and dependency health:

Bash
docker compose ps docker compose logs --tail=150 app docker compose logs --tail=150 db docker compose logs --tail=150 cache

If PostgreSQL never becomes healthy, check readiness directly:

Bash
docker compose exec -T db pg_isready -U taskuser -d taskdb

If Redis is unhealthy:

Bash
docker compose exec -T cache redis-cli ping

If the application cannot read the database secret, confirm the secret is mounted without printing it:

Bash
docker compose exec -T app sh -lc 'test -s /run/secrets/postgres_password && echo secret-mounted'

If port 3000 cannot bind, identify the current listener:

Bash
sudo ss -lntp | grep ':3000'

Verify: Fix one layer at a time in this order: Compose validation, dependency health, secret mount, application logs, then host port binding.

Step 14 — Run the Final End-to-End Verification

Run the final checks:

Bash
cd ~/task-api docker compose config -q docker compose ps curl -fsS http://127.0.0.1:3000/health curl -fsS http://127.0.0.1:3000/tasks sudo ss -lntp | grep -E ':(3000|5432|6379)\b' || true ls -lh backups/

Verify: The Compose file validates, PostgreSQL and Redis are healthy, /health returns status: ok, and /tasks still includes the persistence-test task from Step 10. Only the intended localhost API port is published. A non-empty dump exists from Step 11; verify an off-server copy and a restore before relying on it for recovery.

Node.js, PostgreSQL, and Redis on one VM.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month · 14-day money-back guarantee

Deploy Your Server

Cleanup (Optional)

Keep the stack running if you intend to use it. To pause this project's containers without removing them, use Docker Compose stop:

Bash
cd ~/task-api docker compose stop docker compose ps -a

The services now show a stopped state. The containers, named volumes, project files, secrets, and local backups remain available.

To resume the stopped containers:

Bash
cd ~/task-api docker compose start docker compose ps

Wait for PostgreSQL and Redis to become healthy, then verify the API again:

Bash
curl -fsS http://127.0.0.1:3000/health curl -fsS http://127.0.0.1:3000/tasks

To remove only the project's containers and network while retaining the named data volumes, run:

Bash
cd ~/task-api docker compose down

A later docker compose up -d recreates the containers and reconnects this project's named volumes. Keep the same project directory and Compose project name so the intended volumes are reused. Docker's down reference explains the resources removed by default.

⚠️ Warning: Adding -v to docker compose down deletes this project's named volumes, including PostgreSQL and Redis data. Deleting ~/task-api also removes compose.yaml, .env, the database secret, and every local dump in ~/task-api/backups. Keep these files and volumes until you have verified independent recovery copies and explicitly decided to retire their data.

Verify: After a pause and restart, /health succeeds and the persistence-test task remains in /tasks. After an intentional down without -v, retain the named volumes and project directory for a later up -d.

Conclusion

You now have a multi-container Docker Compose application running on Ubuntu 24.04 with a Node.js API, PostgreSQL, Redis, health-check-aware dependency startup, a mounted database secret, private service networking, named-volume persistence, backup steps, troubleshooting, and cleanup instructions.

Select a VM size based on application, database, cache, traffic, and storage measurements. Refer to current Raff pricing rather than a hard-coded tutorial price. Docker Compose is a practical fit for single-host deployments; when your architecture requires scheduling workloads across multiple nodes, evaluate an orchestrator such as Managed Kubernetes instead.

For the operating model, continue with Docker Compose for Production. For host preparation, use Docker and Compose installation.

Was this article helpful?
Serdar Tekin
Serdar Tekin
Co-Founder & CTO

Co-Founder & CTO at Raff, focused on cloud infrastructure, systems architecture, security, reliability, and production operations.

Run your Node.js, PostgreSQL and Redis stack on one Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

14-day money-back guarantee

Frequently asked questions

How do I install Docker Compose on Ubuntu 24.04?
With Docker Engine installed from Docker's official repository, install the docker-compose-plugin package and verify it with docker compose version. Use the Compose plugin for this tutorial; the standalone docker-compose command is a legacy compatibility option.
Does depends_on wait until PostgreSQL is ready?
Docker Compose waits for PostgreSQL readiness when depends_on uses condition: service_healthy and the database defines a working health check. Startup order alone does not prove that PostgreSQL accepts connections.
Should I put database passwords in compose.yaml?
Store database passwords in protected secret files and grant access only to services that need them. Keep secrets out of Git, align the app's runtime user with the secret-file owner, and verify read access without printing the password.
Does docker compose down delete database data?
A normal docker compose down removes containers and the project network but keeps named volumes. Adding -v deletes the project's named volumes and their database contents. Keep independent, tested backups before retiring persistent data.
Can Docker Compose be used in production?
Docker Compose can run single-host production workloads with private service networking, HTTPS, health checks, monitoring, controlled updates, and tested off-server backups. It does not schedule workloads across multiple hosts.