A local dev stack with Docker Compose: Go API, Postgres, Redis and migrations
Part 3 of the shorty series: one compose.yaml for the Go API, Postgres 18 and Redis 8, with a one-shot migrate service, idempotent seed data, named volumes and healthchecks. Plus the Postgres 18 volume path change and a seed that failed on the first run.
shorty now has an HTTP API and a Postgres layer with pgx and sqlc. To run it you need Postgres, Redis, the schema migrated and some data to click on. Doing that by hand every time is how a "quick test" turns into half an hour of setup.
In this blog we will write one compose.yaml that starts the whole thing with docker compose up: Postgres, Redis, a one-shot migration, a one-shot seed and the Go API. This is part 3 of the shorty series. Level is beginner, but you should know what an image and a container are. If not, Docker from zero covers that.
I used Docker 29.8.2 with Compose v5.5.0 on a Mac, Postgres 18.7 (postgres:18-alpine) and Redis 8.10.3 (redis:8-alpine).
The services
Five services in one file, in the order they start:
postgres (healthy) --> migrate (exits 0) --> seed (exits 0)
\
+--> api <-- redis (healthy)
The api waits for the migration to finish and for Redis to be healthy. It doesn't wait for the seed, that's just data for me to click on.
Postgres
name: shorty
x-db-env: &db-env
DATABASE_URL: postgres://shorty:shorty@postgres:5432/shorty?sslmode=disable
services:
postgres:
image: postgres:18-alpine
environment:
POSTGRES_USER: shorty
POSTGRES_PASSWORD: shorty
POSTGRES_DB: shorty
ports:
- "127.0.0.1:${PG_PORT:-5432}:5432"
volumes:
# Postgres 18 images keep data under /var/lib/postgresql/18/docker,
# so the volume goes on /var/lib/postgresql (not .../data as before 18).
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U shorty -d shorty"]
interval: 2s
timeout: 3s
retries: 15
A few things in here are worth a line each.
x-db-env is an extension field with a YAML anchor. Compose ignores keys that start with x-, so it's a safe place to keep the database URL once and reuse it with <<: *db-env in two services.
The hostname in that URL is postgres, the service name. Inside the Compose network, every service can reach the others by name. localhost inside the api container is the api container itself, not your laptop and not Postgres. I wrote more about that in Docker networking explained.
The port is published on 127.0.0.1 only, so the database isn't open to your whole Wi-Fi. I published it at all because I want to run psql and the Go integration tests from the host.
Now the volume. Postgres 18 changed where the official image keeps its data. Before 18, everyone mounted the volume on /var/lib/postgresql/data. From 18 the image sets PGDATA=/var/lib/postgresql/18/docker and declares the volume at /var/lib/postgresql. I checked the image to be sure:
docker image inspect postgres:18-alpine --format '{{range .Config.Env}}{{println .}}{{end}}' | grep PGDATA
PGDATA=/var/lib/postgresql/18/docker
I wanted to know what happens if you copy an old compose file with .../data, so I started a throwaway Postgres 18 container with a fresh volume on the old path. It didn't start at all. It exited with code 1 and this (cut short):
Error: in 18+, these Docker images are configured to store database data in a
format which is compatible with "pg_ctlcluster" (specifically, using
major-version-specific directory names).
...
Counter to that, there appears to be PostgreSQL data in:
/var/lib/postgresql/data (unused mount/volume)
...
The suggested container configuration for 18+ is to place a single mount
at /var/lib/postgresql which will then place PostgreSQL data in a
subdirectory, allowing usage of "pg_upgrade --link" without mount point
boundary issues.
So at least it fails loudly, even on an empty volume. The point of the change is in the last line: with one mount on /var/lib/postgresql, the data for 18 and a future 19 can live side by side, and pg_upgrade --link works across them.
pgdata is a named volume, declared at the bottom of the file:
volumes:
pgdata:
Named volumes survive docker compose down. They are only removed with down -v. That is what you want in dev: stop everything at night, data is still there in the morning.
Redis as a cache only
redis:
image: redis:8-alpine
# A cache only: no snapshots, no AOF, evict least recently used keys when full.
command: ["redis-server", "--save", "", "--appendonly", "no", "--maxmemory", "64mb", "--maxmemory-policy", "allkeys-lru"]
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 2s
timeout: 3s
retries: 15
shorty only uses Redis to cache hot links, and Postgres has the truth. So basically there's no point writing Redis to disk. --save "" turns off snapshots, --appendonly no turns off the append log, and allkeys-lru throws out old keys when it hits 64 MB instead of failing writes. No volume either. If Redis restarts empty, shorty just reads Postgres for a bit.
A one-shot migrate service
migrate:
build: .
image: shorty:dev
command: ["/shorty", "migrate", "up"]
environment:
<<: *db-env
depends_on:
postgres:
condition: service_healthy
restart: "no"
This uses the same image as the api. The binary has the migrations embedded (see part 2), and the Dockerfile uses CMD, not ENTRYPOINT, so command: replaces it cleanly. Same reason I gave in why your Docker image should use CMD and not ENTRYPOINT, and it's the same trick ECS will use later.
condition: service_healthy waits for pg_isready to pass, not just for the container to start. Without it the migration races Postgres and can easily lose. Stop your app racing the database goes through all the depends_on conditions in detail, so I won't repeat it here.
restart: "no" is the default, but I like having it written down for a job that is supposed to exit.
Seed data
seed:
image: postgres:18-alpine
command: ["psql", "-v", "ON_ERROR_STOP=1", "-f", "/seed/seed.sql"]
environment:
PGHOST: postgres
PGUSER: shorty
PGPASSWORD: shorty
PGDATABASE: shorty
volumes:
- ./seed:/seed:ro
depends_on:
migrate:
condition: service_completed_successfully
restart: "no"
The seed reuses the Postgres image just for its psql, so there's nothing extra to pull. service_completed_successfully means "the migrate container exited with code 0". ON_ERROR_STOP=1 makes psql exit non-zero on the first error instead of carrying on.
That flag earned its place on the very first run itself. My seed file had a link with the code go. The table has CHECK (length(code) BETWEEN 3 AND 32), so Postgres refused it:
seed-1 | psql:/seed/seed.sql:7: ERROR: new row for relation "links" violates check constraint "links_code_check"
seed-1 | DETAIL: Failing row contains (1, go, https://go.dev/doc/, 0, 2026-11-19 06:41:02.124705+00).
and docker compose ps -a showed seed Exited (3). The api came up anyway, because it doesn't depend on the seed. I think that's the right call for dev data, but it means you have to actually look at ps -a to notice. I renamed the code to golang. The file is idempotent, so running it again is safe:
-- Local dev seed data. Safe to run many times.
INSERT INTO links (code, url) VALUES
('golang', 'https://go.dev/doc/'),
('pgx', 'https://github.com/jackc/pgx'),
('sqlc', 'https://docs.sqlc.dev/'),
('blog', 'https://fenixara.com/')
ON CONFLICT (code) DO NOTHING;
The api
api:
build: .
image: shorty:dev
environment:
<<: *db-env
REDIS_URL: redis://redis:6379/0
BASE_URL: http://localhost:${API_PORT:-8080}
LOG_LEVEL: debug
CLICK_FLUSH_INTERVAL: 2s
ports:
- "127.0.0.1:${API_PORT:-8080}:8080"
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_healthy
restart: unless-stopped
# Hardening, explained in the next part of the series.
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
CLICK_FLUSH_INTERVAL: 2s is shorter than the default 5s so I can see click counts move while I test. The last three lines lock the container down. They're the topic of the next post, for now just know shorty runs fine with them.
Both migrate and api have build: . and image: shorty:dev. When I ran docker compose up --build the output said Image shorty:dev Built twice. It is built once really, the second one is all cache hits. It looked a bit odd though.
Port already allocated
My first up didn't get far:
Error response from daemon: failed to set up container networking: driver failed programming external
connectivity on endpoint shorty-postgres-1 (...): Bind for 0.0.0.0:55432 failed: port is already allocated
Something else on my machine already had that port. This is exactly why the ports are ${PG_PORT:-5432} and ${API_PORT:-8080}: the default is the normal port, and you override it from the shell without editing the file. I picked two free ones:
PG_PORT=56543 API_PORT=58931 docker compose up -d --build
For the rest of this post I'll write the default 8080 and 5432, use whatever you set.
Running it
docker compose up -d --build
docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'
SERVICE STATUS
api Up 13 seconds (healthy)
migrate Exited (0) 4 seconds ago
postgres Up 16 seconds (healthy)
redis Up 25 seconds (healthy)
seed Exited (0) 4 seconds ago
Two "Exited (0)" lines is what you want here. Those are the one-shot jobs. The api shows healthy because the image has a HEALTHCHECK that runs /shorty healthcheck.
docker compose logs migrate
migrate-1 | OK up 00001_create_links.sql (5.05ms)
Now click a seeded link and look at Redis:
curl -si localhost:8080/golang | head -1
docker compose exec redis redis-cli --scan --pattern 'shorty:*'
docker compose exec redis redis-cli ttl shorty:link:golang
curl -s localhost:8080/links/golang
HTTP/1.1 302 Found
shorty:link:golang
86392
{"code":"golang","url":"https://go.dev/doc/","short_url":"http://localhost:8080/golang","clicks":1,"created_at":"2026-11-19T06:41:11.436705Z"}
The first redirect missed Redis, read Postgres and cached the link for 24 hours. A couple of seconds later the click counter flushed and clicks went to 1.
Next I wanted to see the graceful shutdown work with Compose. I hit the pgx link five times and stopped the api straight away, inside the 2 second flush window:
for i in 1 2 3 4 5; do curl -s -o /dev/null localhost:8080/pgx; done
docker compose stop -t 20 api
docker compose exec postgres psql -U shorty -t -c "select code, clicks from links where code='pgx'"
pgx | 5
All five were saved. docker compose stop sends SIGTERM, shorty finishes its requests, flushes the counts and exits. -t 20 is how long Compose waits before it sends SIGKILL, the default is 10 seconds.
Integration tests against the stack
The Postgres test from part 2 needs a real database. The compose Postgres is right there on the host port:
SHORTY_TEST_DATABASE_URL='postgres://shorty:shorty@localhost:5432/shorty?sslmode=disable' \
go test -count=1 -run TestPostgres ./internal/links/
It passed in about 1.4 seconds for me. Running that same test in CI is coming later in the series.
Cleaning up
docker compose down -v
-v deletes the pgdata volume as well. Leave it off if you want to keep your data. I always check nothing is left over, because I share this Docker with a lot of other projects:
docker ps -a --filter name=shorty
docker volume ls --filter name=shorty
Both came back empty. If you've used Compose for something like my Ghost migration to Docker Compose, this is the same tool, just with a migrate step in front.