15 min read
Docker Compose explained: Postgres and Redis
In one sentence: Docker Compose starts several containers from one file, compose.yaml, which describes each of them: its image, its variables, its ports and its volumes. With docker compose up, the whole shop (the API, PostgreSQL and Redis) starts in order and on a network of its own; with docker compose down, it stops.
What you will learn
- Read a compose.yaml piece by piece, service by service.
- Start the services in order with depends_on and healthchecks.
- Use docker compose up, ps, logs, exec and down, and know what down -v deletes.
- Share the attempt limit between two copies of the API, with Redis.
Before you start, read: 06-networks.md
The problem
Section titled “The problem”Picture Luis joining the project and wanting the shop on his laptop. Ana sends him the commands from lessons 5 and 6, more or less these:
docker network create shopdocker run -d --name db --network shop -v data:/var/lib/postgresql \ -e POSTGRES_USER=shop -e POSTGRES_PASSWORD=YOUR-PASSWORD postgres:18docker run -d --name api --network shop --env-file .env \ -e DATABASE_URL=postgres://shop:YOUR-PASSWORD@db:5432/shop \ -p 127.0.0.1:3000:3000 shop-apiThe migrations and Redis are missing. The names have to match, the password goes in two places, and the order matters: if the API starts before PostgreSQL accepts connections, it fails. Luis gets one letter wrong and loses the afternoon.
Docker Compose turns those commands into a file, and the whole shop starts with docker compose up.
The analogy
Section titled “The analogy”The analogy
Think about how a bakery opens in the morning. First the oven is turned on, and you wait for it to reach 200 degrees. Then the first batch is baked. Only then is the door opened. If someone skips the wait, the bread comes out raw.
The owner doesn’t explain this to every new employee: she writes it on a sheet stuck to the wall. Whoever arrives follows the sheet, and the bakery opens the same way every day.
compose.yaml is that sheet. The oven at 200 degrees is PostgreSQL being healthy; the first batch, the migrations; opening the door, starting the API. docker compose up is following the sheet, and docker compose down, closing at the end of the day.
Where the analogy breaks down
- An employee notices if something smells odd. Compose only checks what the sheet says.
- The sheet says how to open, not what to do if the oven goes out at noon. Compose orders the startup; if PostgreSQL goes down later, the API keeps running and its
/healthanswers503. - Closing with
down -vis closing and throwing out the stock: this project’s database, not anyone else’s.
How it really works
Section titled “How it really works”One file instead of three commands
Section titled “One file instead of three commands”Docker ComposeA Docker tool that starts several containers from a file, compose.yaml, that describes each one with its image, its variables, its ports and its volumes. docker compose up starts them all, in order and on a network of their own, and docker compose down stops them.Go to definition is the part of Docker that starts several containers from a file. You installed it with Docker in the introduction, and docker compose version tells you which one you have.
The file is called compose.yaml and lives in the project’s folder. It’s written in YAML, a text format for data, like JSON but without braces: the indentation says what goes inside what, and # starts a comment. This is the shop’s:
# The whole shop with one command (Phase 7, lesson 7): the API, PostgreSQL and Redis, each in its# own container, on a network of their own where they find each other by the service name (db,# redis).# docker compose up --build starts everything (Ctrl + C stops it)# docker compose down stops it and deletes the containers; with -v, the data too## The secrets aren't written here: this file goes to Git. They come from your .env, which Compose# reads on its own (copy it from .env.example): ${POSTGRES_PASSWORD} is replaced with its value.
# The project's name: the containers are called shop-api-1, shop-db-1…name: shop
services: # PostgreSQL 18, pinned by its digest. No published port: only the shop's containers see it, and # it doesn't clash with the PostgreSQL on your computer (5432). db: image: postgres:18@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336 # The image creates the user and the database the first time it starts with the volume empty. environment: POSTGRES_USER: shop POSTGRES_DB: shop POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is missing in .env (see .env.example)} # The data, in a named volume: it survives docker compose down (not down -v). volumes: - data:/var/lib/postgresql # Healthy when it accepts connections: until then, whoever depends on it waits. healthcheck: test: ['CMD', 'pg_isready', '-U', 'shop', '-d', 'shop'] interval: 2s timeout: 5s retries: 15
# Redis 8, pinned by its digest: the attempts of the limits, shared by all the copies of the API. # No published port, like db. Without saving anything to disk: if it restarts, the attempts are # forgotten, and nothing happens. redis: image: redis:8@sha256:2c2dff791878316e3b083188be0d578423b24813cdda5de0e80ea4f7b3e6bfd6 command: ['redis-server', '--save', '', '--appendonly', 'no'] healthcheck: test: ['CMD', 'redis-cli', 'ping'] interval: 2s timeout: 5s retries: 15
# A task, not a server: it applies the migrations, loads the practice data (the accounts always; # the products, only if there are none) and ends. With the API's image. migrate: build: . command: ['sh', '-c', 'node scripts/migrate.ts && node scripts/seed.ts'] environment: DATABASE_URL: postgres://shop:${POSTGRES_PASSWORD}@db:5432/shop depends_on: db: condition: service_healthy # The image's HEALTHCHECK asks the API, and there's no API here. healthcheck: disable: true
# The API, built with this folder's Dockerfile. api: build: . # Your configuration (the secrets, the identity provider…), from .env. What changes inside # Compose goes in environment, which wins over env_file: the database and Redis, by their name. env_file: .env environment: DATABASE_URL: postgres://shop:${POSTGRES_PASSWORD}@db:5432/shop REDIS_URL: redis://redis:6379 # Only on your computer (127.0.0.1). A range, and not a port: with docker compose up --scale # api=2, each copy takes a free one, 3000 or 3001 (docker compose ps says which). ports: - '127.0.0.1:3000-3001:3000' # It doesn't start until the database and Redis are healthy and the migrations have finished # well. depends_on: db: condition: service_healthy redis: condition: service_healthy migrate: condition: service_completed_successfully
volumes: data:compose.yaml goes to Git, like the Dockerfile: it describes the shop, without a single secret.
One project, four services
Section titled “One project, four services”name: shop: the project’s name. Compose puts it in front of everything it creates: the containers are calledshop-db-1,shop-api-1… (the number is the copy). Withoutname, it would use the folder’s name.services: each service is one of the shop’s programs, and each one runs in its own container. There are four:db,redis,migrateandapi.image: postgres:18@sha256:…: the image that’s downloaded. After the@comes its Digest (of an image)The SHA-256 hash that names a Docker image by its content, written as sha256 followed by 64 characters. A digest always names exactly the same image, and Docker checks it when downloading it, so pinning an image by its digest keeps it from changing unless you decide so.Go to definition, which pins it byte for byte; lesson 8 explains it.build: .: instead of downloading an image, it builds one with this folder’sDockerfile, the one from lesson 4. Compose calls itshop-api, like yours: it replaces it.command: changes the image’sCMD. Redis starts without saving anything to disk;migrate, with the same image as the API, runs the two scripts from Phase 5 and ends.
migrate isn’t a server but a task: it applies the missing migrations, loads the practice data and exits. It runs on every up, and migrations already applied aren’t repeated. For that, the Dockerfile now also copies db/ and those two scripts into the final image.
The variables come from your .env
Section titled “The variables come from your .env”Each container’s Environment variableA name with a value, like PORT=3000, that a program receives when it starts from whoever starts it, for example the shell. It lets you configure the program without changing its code and give it secrets without writing them in it.Go to definition are written in two ways:
environment: a list of variables, like several-eindocker run.env_file: .env: all the ones in your.env, like--env-file .env. That’s how the API gets its secrets from Phase 6.
If a variable is in both, environment wins, as -e won in lesson 6. That’s why your .env can keep the localhost DATABASE_URL, to start the API without Docker, while inside Compose the one with db applies.
And Compose uses .env for something else: it reads it on its own, if it’s next to compose.yaml, and replaces each ${POSTGRES_PASSWORD} in the file with its value. With ${POSTGRES_PASSWORD:?message}, if it’s missing, it stops and writes the message.
The PostgreSQL password is new, and you generate it with openssl rand -hex 24: 24 random bytes, written in hexadecimal, only with 0–9 and a–f. Not with -base64, like the Phase 6 secrets, because this one goes inside a URL, postgres://shop:PASSWORD@db:5432/shop, and base64 uses /, + and =, which mean something else in a URL.
The PostgreSQL image only uses POSTGRES_USER, POSTGRES_DB and POSTGRES_PASSWORD the first time, with the volume empty: it creates the shop user, its database and its password. After that, they’re saved in the volume.
Ports, volumes and a network you don’t write
Section titled “Ports, volumes and a network you don’t write”ports: '127.0.0.1:3000-3001:3000' Publishing a portConnecting a port on your computer to a port in a container, with the -p option of docker run, so that whatever reaches the first one goes into the second. Without an IP in front, Docker opens the port on all of your computer’s addresses, and anyone on your network can reach it; with 127.0.0.1 in front, only your computer can.Go to definition the API’s port 3000, only on your computer, as in lesson 6. On the left goes a range: each copy of the API takes a free port from it. With one copy, 3000 or 3001; with two, one each. With a single port, the second copy couldn’t start.
db and redis don’t publish anything: only the shop’s containers see them. Your PostgreSQL from Phase 5 stays on 5432 without clashing.
volumes inside db mounts the data volume on the folder where PostgreSQL keeps its files, like -v in lesson 5. The volumes: at the end declares that volume, and Compose calls it shop_data: a different one from lesson 5’s data, and it starts empty.
The Docker networkA private network Docker creates inside your computer so containers can talk to each other, each one with its own IP address. On a network you create yourself, with docker network create, each container finds the others by name, because Docker acts as their DNS.Go to definition isn’t written. Compose creates shop_default and puts the four services on it, each with the service’s name as its name on the network: the API reaches db and redis by their names, with Docker’s DNS from lesson 6.
Starting in order: depends_on and the healthchecks
Section titled “Starting in order: depends_on and the healthchecks”depends_on says what a service depends on. Written on its own, Compose waits for the other container to start, but PostgreSQL takes a few seconds to accept connections. That’s why each dependency carries a condition:
service_healthy: waits for the other one to be healthy.service_completed_successfully: waits for the other one to end with exit code 0, without an error.
Healthy is decided by a HealthcheckA command Docker runs every few seconds inside a container to find out whether its program really works, not just whether it’s running. If it ends well, the container is healthy; after several failures in a row, it’s unhealthy. Compose uses it to wait for a service before starting the ones that depend on it.Go to definition: a command Docker runs inside the container, like the HEALTHCHECK from lesson 4. In db it’s pg_isready -U shop -d shop, which asks PostgreSQL whether it accepts connections; in redis, redis-cli ping, which expects a PONG. interval: 2s asks every two seconds; timeout: 5s gives it five to answer, and after fifteen failures in a row (retries: 15), it marks it unhealthy.
The API already brings its own, the one from lesson 4, which asks /health. migrate uses that image, but it isn’t the API: disable: true takes the healthcheck away.
This is how the startup goes:
- db and redisstart, and Docker asks their healthcheck
db healthy
- migrateapplies the migrations and loads the data
ends with code 0, and redis healthy
- apistarts, with PostgreSQL and Redis ready
If migrate fails, the API doesn’t start: better stopped than serving with half-made tables.
The everyday commands
Section titled “The everyday commands”They’re all typed in the folder of compose.yaml and start with docker compose:
| Command | What it does |
|---|---|
up --build -d |
Builds the image if something changed, creates the network and the volume, and starts everything in order |
ps |
The project’s containers; with -a, also the ones that ended, like migrate |
logs -f api |
The API’s logs, and it keeps writing the new ones |
exec db psql -U shop |
Opens psql inside the PostgreSQL container |
port api 3000 |
Which port on your computer the API’s 3000 ended up on |
down |
Stops and deletes the containers and the network; the volume stays |
down -v |
The same, and it also deletes the volume: the data |
Word by word, the first one:
up: creates whatever is missing and starts the services.--build: first builds the image ofbuild: .. Without it, Compose uses the one it already has, even if you’ve changed the code.-d: in the background, likedocker run -din lesson 1. Without it, Compose mixes everyone’s logs in your terminal, and Ctrl + C stops it all.
exec already gives you a terminal, without -it. And down doesn’t delete the images: the next up takes seconds.
Two copies of the API, a single count in Redis
Section titled “Two copies of the API, a single count in Redis”In the Phase 6 rate limiting lesson, the attempt limit kept its count in the server’s memory. With two copies of the API, each one keeps its own: an attacker tries ten passwords on one and ten on the other.
The solution is a shared store: Redis, the Key-value storeA database that stores each piece of data under a name, its key, and gives it back when you give it that name, like a dictionary. It doesn’t search by conditions or combine data, and in exchange it’s very fast. Redis is the best known, and it’s widely used as a cache.Go to definition from Phase 5. It’s a separate server that keeps the data in memory, and both copies ask the same one. The shop only uses it if REDIS_URL exists, and compose.yaml sets it:
// With REDIS_URL (in Docker Compose), the attempts go to Redis, shared by all the copies of the// API; without it, to this server's memory, as until now.const store = config.REDIS_URL ? createRedisStore(connectRedis(config.REDIS_URL)) : createMemoryStore();Without REDIS_URL, as with npm start, everything stays as in Phase 6. The Redis store has the same two functions as the memory one, so the limiter doesn’t change:
// None of the shop's windows is longer than an hour: a key nobody touches in a day is not needed.const ONE_DAY = 24 * 60 * 60 * 1000;
// Each key's attempts, in a Redis sorted set: each attempt is a member, and its score, the instant// in ms. Redis keeps them ordered by score, so "delete the ones before since" or "give all of them,// from oldest to newest" is one command.// prefix: in front of each key, so they don't mix with other data in the same Redis.export function createRedisStore(client: RedisClient, prefix = 'limits:'): LimitStore { return { async attempts(key, since) { // MULTI: both commands, together and in order, without another one sneaking in between. const [, attempts] = await client .multi() .zRemRangeByScore(prefix + key, '-inf', since) // the ones that left the window, out .zRangeWithScores(prefix + key, 0, -1) // the ones that are left .execTyped(); return attempts.map((attempt) => attempt.score); }, async record(key, instant) { await client .multi() // The member, unique: two attempts in the same millisecond are two attempts. .zAdd(prefix + key, { score: instant, value: `${instant}-${randomUUID()}` }) .pExpire(prefix + key, ONE_DAY) .execTyped(); }, };}// Each function is atomic, but check and record (rate-limits.ts) are two trips to Redis: between// one and the other, the other copy of the API can record an attempt. In the worst case one too// many slips in, right at the limit; to slow down brute force, that's enough. If it had to be// exact, a Lua script would do both things inside Redis, at once.- A sorted set per key: each attempt is a member, with its instant as its score. Redis keeps them in order, so deleting the ones that left the window is a single command.
multi()sends several commands together: Redis runs them one after the other, without another one sneaking in between.pExpire: the key expires on its own after 24 hours without attempts.
The last comment admits a gap: between checking and recording, the other copy can slip in an attempt. To slow down brute force, that’s enough.
Try it
Section titled “Try it”The goal: start the whole shop with one command, prove that two copies of the API share the attempt limit, and see what each down deletes.
The outputs are from Docker Engine 29 and Compose 5.5 on a Mac, inside a virtual machine with Linux, like Docker Desktop’s. We captured them with other names and other ports, swapped for the lesson’s: nothing else changes. We’ve removed columns and adjusted spaces so they fit. Your IDs, times and passwords will be different.
Update your project
Section titled “Update your project”You’re working in ~/backend-course/phase-3/shop-api, with the project from lesson 4. Download the step and copy what changes:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/34-compose.tar.gztar -xzf 34-compose.tar.gzcd shop-apicp ../34-compose/compose.yaml ../34-compose/Dockerfile ../34-compose/.dockerignore ../34-compose/.env.example .cp ../34-compose/src/redis-store.ts ../34-compose/src/rate-limits.ts ../34-compose/src/config.ts src/cp ../34-compose/test/redis-store.test.ts ../34-compose/test/compose.test.ts test/npm install redis@6.3.0compose.yaml and redis-store.ts are new. rate-limits.ts chooses the store, config.ts reads REDIS_URL, the Dockerfile also copies db/ and the two scripts, and .dockerignore leaves compose.yaml out.
If your PostgreSQL from Phase 5 is running, it can stay: Compose doesn’t use your computer’s 5432. If the API from lesson 6 is still running, delete it with docker rm -f api: it uses 3000.
Start the shop
Section titled “Start the shop”1. A password for PostgreSQL
openssl rand -hex 24What you will see:
40da6c92412f1e8054dd79a82184746507103bf5c7f906ab48 characters, only numbers and the letters a to f. Add a POSTGRES_PASSWORD= line with yours, which will be different, to your .env.
2. Everything, with one command
docker compose up --build -dWhat you will see:
…[+] up 8/8✔ Image shop-api Built 0.5s✔ Image shop-migrate Built 0.5s✔ Network shop_default Created 0.0s✔ Volume shop_data Created 0.0s✔ Container shop-redis-1 Healthy 3.3s✔ Container shop-db-1 Healthy 3.3s✔ Container shop-migrate-1 Exited 3.7s✔ Container shop-api-1 Started 3.8sLook at the order: db and redis reach Healthy, migrate ends (Exited), and only then does the API start. shop-api and shop-migrate come from the same Dockerfile and share all their layers. The first time, the build steps come first, as in lesson 4, along with the download of PostgreSQL and Redis: it takes a few minutes.
If it says required variable POSTGRES_PASSWORD is missing a value, your .env is missing the line from step 1.
3. Who's running?
docker compose psWhat you will see:
NAME SERVICE STATUS PORTSshop-api-1 api Up 24 seconds (healthy) 127.0.0.1:3000->3000/tcpshop-db-1 db Up 27 seconds (healthy) 5432/tcpshop-redis-1 redis Up 27 seconds (healthy) 6379/tcpAll three, healthy. Only the API has an arrow in PORTS: published on 3000. Yours may be on 3001: Docker takes turns with the ports in the range.
migrate doesn’t show up because it has already ended; docker compose ps -a shows it with Exited (0), without an error. If the API says (health: starting), wait a few seconds.
4. Ask the shop
docker compose port api 3000curl -s localhost:3000/healthWhat you will see:
127.0.0.1:3000{"status":"ok"}If port says 3001, use that port for the rest of the practice. {"status":"ok"}: the API talks to PostgreSQL by its name, db.
5. The API's logs
docker compose logs -f apiWhat you will see:
api-1 | {"level":30,"time":1791955742924,"pid":1,"hostname":"025d78c222c4","msg":"The shop is listening on http://localhost:3000"}api-1 | {"level":30,"time":1791955762372,"pid":1,"hostname":"025d78c222c4","requestId":"221cb67f-071b-46ad-a3d7-3203a563c0bd","method":"GET","path":"/health","status":200,"ms":7,"msg":"request"}api-1 | {"level":30,"time":1791955766521,"pid":1,"hostname":"025d78c222c4","requestId":"84a92b92-d6de-49c1-a05e-722704935e6a","method":"GET","path":"/health","status":200,"ms":1,"msg":"request"}api-1 | {"level":30,"time":1791955769715,"pid":1,"hostname":"025d78c222c4","requestId":"88387d13-d6a0-45f2-b792-55f448cbfcc4","method":"GET","path":"/v2/products","status":200,"ms":149,"msg":"request"}Each line starts with the copy that writes it, api-1. The first one says 3000 even if you got 3001: it’s the port inside the container. The /health ones are the healthcheck and your curl; the last one, a curl to /v2/products from another terminal. -f (follow) stays waiting for new lines: Ctrl + C stops watching, and the API keeps going.
6. Inside PostgreSQL
docker compose exec db psql -U shop -c 'SELECT name, price_cents FROM products;'What you will see:
name | price_cents---------+-------------T-shirt | 2000Mug | 850Hoodie | 3500Cap | 1500(4 rows)exec db runs psql in the db container, and -c hands it the query: the products migrate loaded. Without -c, you go into psql, and \q gets you out.
Two copies, a single limit
Section titled “Two copies, a single limit”7. A second copy of the API
docker compose up -d --scale api=2docker compose psWhat you will see:
…NAME SERVICE STATUS PORTSshop-api-1 api Up 41 seconds (healthy) 127.0.0.1:3000->3000/tcpshop-api-2 api Up 3 seconds (health: starting) 127.0.0.1:3001->3000/tcpshop-db-1 db Up 45 seconds (healthy) 5432/tcpshop-redis-1 redis Up 44 seconds (healthy) 6379/tcp--scale api=2 asks for two api containers. The new one takes the other port in the range. We’ve cut the up lines.
Now, ten wrong passwords for Ana, one to each copy in turn, as in Phase 6:
8. Ten failures, shared out
for i in {1..5}; dofor port in 3000 3001; do printf '%s: ' $port curl -s -o /dev/null -D - --json '{"email":"ana@shop.example","password":"any password at all"}' localhost:$port/v2/session | grep -i '^ratelimit:'donedoneWhat you will see:
3000: ratelimit: "session-email";r=9;t=900, "session-ip";r=29;t=9003001: ratelimit: "session-email";r=8;t=900, "session-ip";r=28;t=9003000: ratelimit: "session-email";r=7;t=900, "session-ip";r=27;t=9003001: ratelimit: "session-email";r=6;t=900, "session-ip";r=26;t=9003000: ratelimit: "session-email";r=5;t=900, "session-ip";r=25;t=9003001: ratelimit: "session-email";r=4;t=900, "session-ip";r=24;t=9003000: ratelimit: "session-email";r=3;t=900, "session-ip";r=23;t=9003001: ratelimit: "session-email";r=2;t=900, "session-ip";r=22;t=9003000: ratelimit: "session-email";r=1;t=900, "session-ip";r=21;t=9003001: ratelimit: "session-email";r=0;t=900, "session-ip";r=20;t=900The inner loop alternates between the two ports, and printf writes which one. Look at r: it goes down one by one even though each request lands on a different copy. With the in-memory store, each copy would start its own count at 9.
9. The eleventh, on both
curl -s -o /dev/null -w '%{http_code}\n' --json '{"email":"ana@shop.example","password":"some other password"}' localhost:3000/v2/sessioncurl -s -o /dev/null -w '%{http_code}\n' --json '{"email":"ana@shop.example","password":"some other password"}' localhost:3001/v2/sessiondocker compose exec redis redis-cli zcard limits:session-email:ana@shop.exampleWhat you will see:
429429(integer) 10429 on both copies: neither lets in someone who has already failed ten times. zcard counts the members of the sorted set: the ten attempts, kept in Redis.
down and down -v
Section titled “down and down -v”Create an account, and see what happens to it when you stop the shop:
10. down: the data stays
curl -s -w '\n' --json '{"email":"marta@example.com","password":"a long sentence only I know"}' localhost:3000/v2/accountsdocker compose downdocker compose up -ddocker compose exec db psql -U shop -c "SELECT email FROM users WHERE email = 'marta@example.com';"What you will see:
{"id":9,"email":"marta@example.com","role":"customer"}[+] down 6/6✔ Container shop-api-1 Removed 0.4s✔ Container shop-api-2 Removed 0.4s✔ Container shop-migrate-1 Removed 0.0s✔ Container shop-redis-1 Removed 0.2s✔ Container shop-db-1 Removed 0.1s✔ Network shop_default Removed 0.1s… email-------------------marta@example.com(1 row)down deletes the five containers and the network, but not the volume: Marta is still there. Ana’s attempts, on the other hand, have been forgotten: Redis doesn’t save anything to disk. Your id may be different.
11. down -v: the data goes
docker compose down -vdocker compose up -ddocker compose exec db psql -U shop -c "SELECT email FROM users WHERE email = 'marta@example.com';"What you will see:
[+] down 6/6✔ Container shop-api-1 Removed 0.2s✔ Container shop-migrate-1 Removed 0.0s✔ Container shop-redis-1 Removed 0.2s✔ Container shop-db-1 Removed 0.1s✔ Volume shop_data Removed 0.0s✔ Network shop_default Removed 0.1s…email-------(0 rows)The line down didn’t have: Volume shop_data Removed. The next up creates an empty volume and migrate loads the practice data again, but Marta left with the volume.
To finish, docker compose down. If you’re not going back to the shop with Docker, docker compose down -v deletes its data too.
You have already seen it
Section titled “You have already seen it”- The
HEALTHCHECKfrom lesson 4. Compose uses it to know the API is ready, anddocker compose psshows it just likedocker ps. - The network from lesson 6.
shop_defaultis theshopnetwork you created by hand, with its DNS. - This course’s CI. Its tests wait for PostgreSQL with
pg_isready, and with step 34 they rundocker compose up, ask the API and finish withdocker compose down -v.
Common mistakes
Section titled “Common mistakes”- Changing
POSTGRES_PASSWORDwhen the volume already exists. PostgreSQL kept the first one, andmigrateends withpassword authentication failed for user "shop". The API stays inCreated, without starting. Put the old password back or, if you don’t care about the data,docker compose down -v. down -vto “start clean.” It deletes the project’s database. To restart without losing anything,docker compose downandup.- Taking for granted that the API is on 3000. With the range, it may get 3001:
docker compose port api 3000tells you. - More copies than ports.
--scale api=3with a range of two leaves the third one inCreated, withall ports are allocated. - Signing in with the practice provider. Inside Compose it answers
500: the API looks for the provider atlocalhost:9000, which inside its container is the API itself, and that address has to be the same for your browser and for the API. With email and password, it works.
Summary
Section titled “Summary”compose.yamldescribes the shop: each service with its image (downloaded or built), its variables, its ports and its volumes.docker compose upcreates the network and starts it all.environmentwins overenv_file, and Compose replaces${VARIABLE}with the values in your.env: secrets never go in the file.depends_onwithservice_healthywaits for a healthcheck to say the service is ready; withservice_completed_successfully, for a task likemigrateto end well.downdeletes containers and network;down -v, the volumes too, with the data.- With Redis, two copies of the API keep a single count of attempts: the eleventh failure is
429on both.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Docker Compose, from Docker’s documentation: what it is and how to get started.
- The services reference:
image,build,environment,ports,depends_on,healthcheckand the rest. - Control startup order:
depends_onand its conditions. - Environment variables precedence: who wins when a variable is in several places.
- Redis sorted sets, from Redis’s documentation: sorted sets.