Skip to main content

Dev tools and workflow · Intermediate · 18 min

Run local development services with Docker Compose while you code on your machine

By Padding · Updated 18 Nov 2026
Docker Engine 29.10 · Docker Compose 5.8 · PostgreSQL 18.7 · Redis 8 · Mailpit 1.34.0 · macOS, Windows (WSL 2) or Linux

You will have PostgreSQL 18, Redis 8, a Mailpit inbox and a small stub payments API running in Docker Compose on 127.0.0.1, with healthchecks, optional profiles, a personal override file and a one-command data reset, while your app keeps running on your own machine.

On this page

Running your whole app inside Compose, as in run an app and PostgreSQL together with Docker Compose, is a good way to ship. Day to day, it can be slow: every code change goes through a container, your debugger has to attach across a boundary, and file watching on macOS and Windows adds lag. A common middle ground is to keep the app on your machine, where your editor, test runner and hot reload work at full speed, and put only the things it talks to in Compose.

In this tutorial you build that setup for a typical web app. You end up with one compose.yaml that runs PostgreSQL 18, Redis 8, a Mailpit inbox that catches outgoing email, and a tiny stub payments API you can edit and rebuild. Every port listens on 127.0.0.1 only, every service reports when it is ready, and you can wipe the data and start fresh with one command.

The examples use a throwaway folder, ~/compose-services-demo. Nothing here depends on your app's language: your app only needs to read connection settings from environment variables.

Step 1 · Check Docker and create the project folder

Docker Compose ships as the docker compose plugin (two words, no hyphen). It is included with Docker Desktop on macOS and Windows. On Linux, install Docker Engine with the docker-compose-plugin package; install Docker Engine on Ubuntu 26.04 covers that.

On Windows, run every command in this tutorial in a WSL 2 terminal (Ubuntu), with WSL integration for that distribution turned on in Docker Desktop's settings. The commands use bash features such as heredocs and subshells that PowerShell and Command Prompt do not support, and keeping the project folder inside the WSL file system also makes bind mounts faster.

Check both versions:

Bash
docker version --format '{{.Server.Version}}'
docker compose version

This tutorial was written against Docker Engine 29.10 and Docker Compose 5.8. Any Compose 5 release understands everything below. If you are on an older Compose 2 release, you need Compose 2.24 or later: docker compose watch arrived in 2.22 and the !override tag in 2.24.

Create the folder layout. The db/init folder holds SQL that PostgreSQL runs on first start, and stub-payments holds the source of the one service you build yourself:

Bash
mkdir -p ~/compose-services-demo/db/init ~/compose-services-demo/stub-payments/src
cd ~/compose-services-demo

If you pay for mobile data by the gigabyte, pull the images once on a cheaper connection (Step 3 shows how). This tutorial uses Alpine-based images where they exist because they are smaller to download and keep on disk, which also helps on laptops with little free space.

Check it worked

docker compose version prints a version line, and running ls inside ~/compose-services-demo shows the two folders db and stub-payments.

Step 2 · Keep the database password out of compose.yaml

The Compose file is something you commit. The password is not. Compose reads a file called .env in the project folder automatically and substitutes its values into compose.yaml, so the password lives there.

Create .env with a random password, private to your user from the moment it exists:

Bash
(umask 077 && printf 'POSTGRES_PASSWORD=%s\n' "$(openssl rand -hex 24)" > .env)

The parentheses run the command in a subshell, so the stricter umask does not stick to your terminal. Now make sure Git never picks up .env or the personal override file you create in Step 7, and commit an example file instead so teammates know what to set:

Bash
cat > .gitignore <<'EOF'
.env
compose.override.yaml
EOF

cat > .env.example <<'EOF'
# Copy to .env and set a value. Generate one with: openssl rand -hex 24
POSTGRES_PASSWORD=
EOF

Check it worked

ls -l .env shows permissions of -rw-------, and cat .env.example shows the variable name with no value. Do not print .env in a shared screen or a recorded call.

Step 3 · Write compose.yaml for PostgreSQL and Redis

Create compose.yaml with the two services every part of the app needs:

YAML
name: services-demo

services:
  db:
    image: postgres:18.7-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_DB: app
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
    ports:
      - "127.0.0.1:5432:5432"
    volumes:
      - db-data:/var/lib/postgresql
      - ./db/init:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 10s

  redis:
    image: redis:8-alpine
    command: ["redis-server", "--appendonly", "yes"]
    ports:
      - "127.0.0.1:6379:6379"
    volumes:
      - redis-data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 10

volumes:
  db-data:
  redis-data:

A few choices in that file are deliberate:

  • name: services-demo fixes the project name, so container and volume names do not change if someone clones the repository into a folder with a different name. Volumes are called services-demo_db-data and services-demo_redis-data.
  • 127.0.0.1: in front of each port. Without it, Docker publishes the port on every network interface, so anyone on the same café or office Wi-Fi can try your database password. On Linux, published ports also skip ufw rules entirely, so the firewall will not save you. Binding to 127.0.0.1 means only your own machine can connect.
  • Named volumes for data, a bind mount for config. db-data and redis-data are named volumes: Docker manages where they live, they survive docker compose down, and they are fast on macOS and Windows. ./db/init is a bind mount: a folder from your project, mounted read-only (:ro), so the SQL you commit is the SQL that runs. For PostgreSQL 18 images, mount the data volume at /var/lib/postgresql, not the older /var/lib/postgresql/data path.
  • ${POSTGRES_PASSWORD:?...} stops Compose with that message if .env is missing, instead of starting a database with an empty password.
  • Healthchecks let Compose tell "the container started" apart from "the service accepts connections". pg_isready and redis-cli ping are both included in their images.

Now add the init script. It creates a second database for your test suite, so tests never touch your development data:

Bash
cat > db/init/01-test-database.sql <<'EOF'
CREATE DATABASE app_test OWNER app;
EOF

PostgreSQL runs files in /docker-entrypoint-initdb.d only when its data directory is empty, which means on the very first start, or after you reset the data in Step 8. Editing this file later has no effect until you reset.

Pull the images now if you are on a good connection:

Bash
docker compose pull

Check it worked

Run docker compose config --quiet. It prints nothing and exits without an error if the file is valid and .env provides the password. To see the result with the password filled in, run docker compose config and look under db: for the ports entry starting 127.0.0.1. Do not paste that full output anywhere public, as it includes the password.

Step 4 · Start the services and point your app at them

Start both services in the background, and wait until both report healthy:

Bash
docker compose up --detach --wait

--wait makes the command return only when every started service is running and passing its healthcheck, or fail if one does not. That makes it a reliable first line in a script that then starts your app or runs migrations.

Check the state and the published ports:

Bash
docker compose ps
docker compose port db 5432
docker compose port redis 6379

Now give your app its connection settings. Keep them in the environment, not in code. Most frameworks read a local env file (.env.local, .env.development or similar); use whichever your framework expects, keep it out of Git, and set values like these:

Text
DATABASE_URL=postgresql://app:<the password from .env>@127.0.0.1:5432/app
TEST_DATABASE_URL=postgresql://app:<the password from .env>@127.0.0.1:5432/app_test
REDIS_URL=redis://127.0.0.1:6379
SMTP_HOST=127.0.0.1
SMTP_PORT=1025

Use 127.0.0.1 rather than localhost. On some systems localhost resolves to the IPv6 address ::1 first, and the ports above are only published on IPv4.

You can poke at both services without installing any client tools on your machine:

Bash
docker compose exec db psql -U app -d app -c 'SELECT current_database(), version();'
docker compose exec redis redis-cli SET greeting hello
docker compose exec redis redis-cli GET greeting

Check it worked

docker compose ps shows both db and redis with a status that includes (healthy). docker compose port db 5432 prints 127.0.0.1:5432. The psql command prints a row with app and a version string starting PostgreSQL 18.7, and redis-cli GET greeting prints hello. Finally, start your own app: it connects without any code changes beyond reading the environment variables.

Step 5 · Add optional services with profiles

Not every task needs every service. You only want the email catcher when you work on sign-up emails, and the payments stub when you work on checkout. Compose profiles handle this: a service with a profiles list only starts when one of its profiles is switched on. Services without profiles, like db and redis, always start.

First, write the stub payments API. It stands in for a real payment provider so you never send test traffic to a paid service. It counts charges in Redis using Redis's plain-text command format, so it needs no npm packages:

Bash
cat > stub-payments/package.json <<'EOF'
{
  "name": "stub-payments",
  "private": true,
  "type": "module"
}
EOF

cat > stub-payments/Dockerfile <<'EOF'
FROM node:26-alpine
WORKDIR /app
COPY --chown=node:node package.json ./
COPY --chown=node:node src ./src
USER node
EXPOSE 4010
CMD ["node", "src/server.js"]
EOF
Bash
cat > stub-payments/src/server.js <<'EOF'
import http from 'node:http';
import net from 'node:net';

const redis = new URL(process.env.REDIS_URL ?? 'redis://redis:6379');

// Sends one inline Redis command and resolves with the integer reply (":<n>\r\n").
function nextChargeNumber() {
  return new Promise((resolve, reject) => {
    const socket = net.connect(Number(redis.port || 6379), redis.hostname);
    socket.setTimeout(2000, () => socket.destroy(new Error('Redis timed out')));
    socket.once('error', reject);
    socket.once('data', (reply) => {
      socket.end();
      resolve(Number(reply.toString().slice(1).trim()));
    });
    socket.write('INCR stub-payments:charges\r\n');
  });
}

const server = http.createServer(async (req, res) => {
  if (req.method === 'POST' && req.url === '/charges') {
    try {
      const n = await nextChargeNumber();
      res.writeHead(201, { 'content-type': 'application/json' });
      res.end(JSON.stringify({ id: `ch_test_${n}`, status: 'succeeded' }));
    } catch (err) {
      res.writeHead(503, { 'content-type': 'application/json' });
      res.end(JSON.stringify({ error: err.message }));
    }
    return;
  }
  res.writeHead(404).end();
});

server.listen(4010, '0.0.0.0', () => console.log('stub-payments listening on 4010'));
EOF

Inside the Compose network the stub listens on all of its own interfaces; the ports entry below still publishes it to your machine on 127.0.0.1 only.

Now add both services to compose.yaml. Paste this block under the redis service, indented to the same level as db: and redis:, and above the top-level volumes: key:

YAML
  mail:
    image: axllent/mailpit:v1.34.0
    profiles: [mail]
    ports:
      - "127.0.0.1:1025:1025"
      - "127.0.0.1:8025:8025"

  payments:
    build: ./stub-payments
    profiles: [payments]
    environment:
      REDIS_URL: redis://redis:6379
    ports:
      - "127.0.0.1:4010:4010"
    depends_on:
      redis:
        condition: service_healthy

Two things to notice. The stub reaches Redis at redis:6379, the service name, because containers in one Compose project share a network; your app on the host uses 127.0.0.1:6379 instead. And depends_on with condition: service_healthy makes Compose wait for the Redis healthcheck to pass before it starts the stub, so the first charge never fails because Redis was still loading.

Start the services with the profiles you want:

Bash
docker compose --profile mail --profile payments up --detach --wait

If you always want the same profiles, set COMPOSE_PROFILES=mail,payments in .env and a plain docker compose up picks them up. --profile "*" switches on every profile at once.

Send a test email from your machine with curl's built-in SMTP support, and create a charge:

Bash
printf 'From: dev@example.test\r\nTo: someone@example.test\r\nSubject: Hello from Compose\r\n\r\nIt works.\r\n' > /tmp/test-mail.txt
curl --silent smtp://127.0.0.1:1025 --mail-from dev@example.test --mail-rcpt someone@example.test --upload-file /tmp/test-mail.txt
curl --silent -X POST http://127.0.0.1:4010/charges

Mailpit accepts any address and never delivers anything onward, so the example.test addresses are safe.

Check it worked

docker compose ps now lists four services. Open http://127.0.0.1:8025 in your browser: the Mailpit inbox shows the "Hello from Compose" message. The curl call to /charges prints something like {"id":"ch_test_1","status":"succeeded"}, and the number goes up each time you run it. To see the profiles at work without starting anything, run docker compose config --services: with no profile active it lists only db and redis, and docker compose --profile "*" config --services lists all four.

Step 6 · Rebuild the stub automatically with docker compose watch

db, redis and mail run images as published. The stub is different: you build it, and you will change it. Rather than running docker compose up --build payments after every edit, let Compose watch the source.

Add a develop section to the payments service in compose.yaml, indented at the same level as its depends_on::

YAML
    develop:
      watch:
        - action: sync+restart
          path: ./stub-payments/src
          target: /app/src
        - action: rebuild
          path: ./stub-payments/package.json

The two rules do different jobs. Changes under src are copied straight into the running container, which is then restarted: fast, and no image build. A change to package.json could change dependencies, so it triggers a full image rebuild and a new container. Watch works only for services with a build section, which is why it sits on payments and not on the database. The image also needs stat, mkdir and rmdir (Alpine has them) and the container's user must be able to write to the target folder, which is what COPY --chown=node:node in the Dockerfile is for.

Start watching in a second terminal, so the file sync messages do not mix with your app's output:

Bash
cd ~/compose-services-demo
docker compose --profile payments watch

Now change the stub. Open stub-payments/src/server.js and change status: 'succeeded' to status: 'succeeded', currency: 'NGN', then save. Watch prints a sync message and restarts the container. Call it again from your first terminal:

Bash
curl --silent -X POST http://127.0.0.1:4010/charges

Stop watching with Ctrl+C when you are done. The containers keep running.

Check it worked

Within a few seconds of saving, the response includes "currency":"NGN", and you did not run any build command yourself. The charge number carried on from the previous step rather than starting at 1 again, because the count lives in Redis, which watch did not restart.

Step 7 · Make personal changes in compose.override.yaml

Sometimes one person's machine needs something different. A common case: you already run PostgreSQL natively on port 5432, so the Compose database cannot take that port. Do not edit compose.yaml for this; your teammates do not have the same problem. Compose reads compose.override.yaml from the same folder automatically and merges it on top, and you listed it in .gitignore in Step 2.

There is a catch with ports. Compose merges ports lists by adding new entries to the old ones, so a plain override would publish the database on both 5432 and 5433, and 5432 would still clash. The !override tag replaces the whole list instead:

YAML
services:
  db:
    ports: !override
      - "127.0.0.1:5433:5432"

Save that as compose.override.yaml, then recreate the database container so it picks up the new port. Your data is in the named volume, so it survives:

Bash
docker compose up --detach --wait db
docker compose port db 5432

Update DATABASE_URL and TEST_DATABASE_URL in your app's env file to use port 5433. Other good uses for this file: a larger shared_buffers setting on a powerful machine, or ports: !reset [] on a service you never connect to from the host. If you run a different Compose file for CI with -f, the override file is not read automatically, so it never leaks into shared pipelines.

Check it worked

docker compose port db 5432 prints 127.0.0.1:5433, and running docker compose config shows only one entry under the db service's ports. Your earlier greeting key is still in Redis, and docker compose exec db psql -U app -d app -c '\l' still lists app_test, so nothing was lost.

Step 8 · Reset the data and clean up

When migrations go wrong or seed data gets messy, the fastest fix is a clean slate. One command stops every service, in every profile, and deletes the project's named volumes.

The first command below deletes all data in this project's PostgreSQL and Redis volumes. Back up anything you want to keep first.

Bash
docker compose --profile "*" down --volumes
docker compose up --detach --wait

The --profile "*" matters: a plain docker compose down only removes services without a profile, so Mailpit and the stub would keep running. --volumes removes the volumes declared in this file and any anonymous ones; it never touches volumes declared as external, and it does not delete your bind-mounted db/init folder. Because the database volume is now empty, PostgreSQL runs db/init/01-test-database.sql again on start.

To reset only Redis and keep the database, stop and remove that one service, then delete its volume by name:

Bash
docker compose rm --stop --force redis
docker volume rm services-demo_redis-data
docker compose up --detach --wait redis

When you are finished with the demo entirely, remove the containers, volumes and the stub image you built, then the folder and the test email file:

Bash
docker compose --profile "*" down --volumes --rmi local
cd ~
rm -rf ~/compose-services-demo /tmp/test-mail.txt

--rmi local removes only images Compose built (the stub), not the PostgreSQL, Redis and Mailpit images you downloaded. Leave those if you plan to use them again, especially on metered data; remove them with docker image rm when you need the disk space.

Check it worked

After the reset, docker compose exec redis redis-cli GET greeting prints (nil), and docker compose exec db psql -U app -d app -c '\l' lists app_test again because the init script ran. After the final clean-up, docker volume ls --filter name=services-demo lists nothing and docker ps shows none of the demo containers.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.