15 min read
Docker Compose in production on a server
In one sentence: Taking the shop to production with Docker Compose is starting on the server the same shop as on your computer, with a file of its own, compose.production.yaml: the secrets are generated there and never leave, Docker starts it again if it crashes or the server reboots, the logs have a limit and a copy of the database is saved every night.
What you will learn
- Read compose.production.yaml and explain what changes compared to your computer's compose.yaml.
- Take the shop to the server with its secrets generated there, and create your admin account.
- Check that everything comes back on its own after a reboot, and put a limit on Docker's logs.
- Schedule a copy of the database every night with a systemd timer, and restore it.
Before you start, read: 02-server-security.md phase-7/07-compose.md
The problem
Section titled “The problem”Picture Ana copying the Phase 7 shop to her server, typing docker compose up -d and going to bed. It works, but with the practice accounts: two of them are admins, with their password published in the course’s README.
A week later, Ana reboots the server after an update, and the shop doesn’t come back: nobody told Docker to start it. Months later, the logs fill the disk. And the day a down -v slips out, there’s no copy of the orders anywhere.
What’s enough on your computer isn’t enough on a server. In this lesson the shop goes up to yours with what it’s missing.
The analogy
Section titled “The analogy”The analogy
Think of someone who cooks at home and opens a restaurant. The recipes are the same, but the place needs more:
- The key to the till is kept at the restaurant, not in the recipe book: the secrets, in a
.envthat only exists on the server. - The cold room comes back on its own after a power cut: the restart policy.
- Old receipts get thrown out, or there’d be no room left in the kitchen: logs with a limit.
- Every night, the accountant copies the books: the copy of the database.
Where the analogy breaks down
- The cold room comes back because it’s electric. Docker only starts again what has a restart policy, and it respects what you stopped yourself.
- The accountant keeps the copy at their own office. This lesson’s copy stays on the server itself: getting it out of there is up to you.
How it really works
Section titled “How it really works”A file for the server: compose.production.yaml
Section titled “A file for the server: compose.production.yaml”The 35-production folder brings Phase 7’s compose.yaml, for your computer, and one for the server, compose.production.yaml, which you pick with -f (file). Both describe the same four services. This is PostgreSQL:
# PostgreSQL 18, pinned by its digest. No published port: only the shop's containers see it. The# internet doesn't reach it.db: image: postgres:18@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336 restart: unless-stopped environment: POSTGRES_USER: shop POSTGRES_DB: shop # Without a value, Compose doesn't start and says so: a database on the internet without a # password is an open door. POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is missing in .env (see .env.production.example)} # The data, in a named volume: it survives down and restarts (not down -v). volumes: - data:/var/lib/postgresql healthcheck: test: ['CMD', 'pg_isready', '-U', 'shop', '-d', 'shop'] interval: 2s timeout: 5s retries: 15restart: unless-stopped: the Restart policyThe rule that tells Docker what to do when a container stops. With unless-stopped, Docker starts it again if it crashes and every time the server boots, unless you stopped it yourself.Go to definition, in the next section.${POSTGRES_PASSWORD:?…}: with no password in.env, Compose starts nothing and prints the message.- No
ports: PostgreSQL isn’t published, and neither is Redis. Only the shop’s containers can see them.
migrate changes in two ways:
# A task, not a server: it applies the migrations, loads the sample products (if there are none)# and ends. --no-accounts: the practice accounts are not loaded.migrate: # build and image together: "up --build" builds the image and gives it this name; if you set # IMAGE in .env (lesson 6), Compose uses that published image instead of yours. build: . image: ${IMAGE:-shop-api} command: ['sh', '-c', 'node scripts/migrate.ts && node scripts/seed.ts --no-accounts'] 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: truebuild: .next toimage: ${IMAGE:-shop-api}:up --buildbuilds the image on the server and calls itshop-api.:-means “ifIMAGEdoesn’t exist, use this.” In lesson 6,IMAGEwill name the image GitHub publishes.--no-accounts: it loads the sample products, not the practice accounts. You’ll create your admin account with a script in the step,create-admin.
And the API:
# The API, with the same image as migrate.api: build: . image: ${IMAGE:-shop-api} restart: unless-stopped # Your configuration, 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 the server itself (127.0.0.1): nginx talks to it from there, and the internet doesn't # reach it. A range, as in compose.yaml: with up --scale api=2, each copy takes a port (3000 or # 3001), and nginx has both in its upstream. ports: - '127.0.0.1:3000-3001:3000' depends_on: db: condition: service_healthy redis: condition: service_healthy migrate: condition: service_completed_successfully127.0.0.1:3000-3001:3000 is the rule from lesson 2: since Docker bypasses ufw, the API is published only on the server’s own address. It can’t be reached from outside; in lesson 4, nginx will talk to it from inside.
The last piece pins the network:
# The shop's network, with the subnet pinned. What reaches the API through a published port seems to# it to come from this network's gateway (the first address: 172.18.0.1), and not from the visitor# or from nginx. That's the address the API believes to be trustworthy (TRUSTED_PROXY in# .env.production.example), and pinning the subnet keeps it from changing. If another Docker network# on the server already uses 172.18.0.0/16, docker compose up fails with "Pool overlaps with other# one on this address space": change the subnet here and TRUSTED_PROXY's address in .env.networks: default: ipam: config: - subnet: 172.18.0.0/16Docker’s internal network has its own range of addresses, and Compose picks a free one when it creates it. Pinning it keeps the address the API sees nginx arriving from, 172.18.0.1, from changing. Today it does nothing; in lesson 4, the API will use it to know each visitor’s IP.
Inside, 0.0.0.0 and the node user
Section titled “Inside, 0.0.0.0 and the node user”In Phase 3 we told you that a public server listens on 0.0.0.0, all the machine’s addresses. Inside the container, the API listens on 0.0.0.0 (the HOST variable in the Dockerfile), so Docker can pass the requests on to it. On the server, it’s only published on 127.0.0.1.
And in Phase 1 we told you your program would listen on 3000 as its own user. It’s node, a user with no privileges that comes with the image, not root.
If it crashes, it comes back: the restart policy
Section titled “If it crashes, it comes back: the restart policy”With no policy, a container that stops stays stopped. The shop’s, unless-stopped, means “start it again, unless I’m the one who stopped it.” This is what it looks like when you kill the API’s process from the server:
$ sudo kill -9 $(docker inspect --format "{{.State.Pid}}" shop-api-1)$ docker compose -f compose.production.yaml ps --format "table {{.Name}}\t{{.Status}}" apiNAME STATUSshop-api-1 Up 2 seconds (health: starting)$ docker inspect --format "{{.RestartCount}}" shop-api-11A moment later it’s running again (Up 2 seconds), with one restart counted. With docker compose stop api, on the other hand, it stays Exited.
| Policy | If it crashes | If you stop it | When the server boots |
|---|---|---|---|
no, the default |
Stays stopped | Stays stopped | Stays stopped |
always |
Comes back | Stays stopped | Comes back, even if you stopped it |
unless-stopped |
Comes back | Stays stopped | Comes back, unless you stopped it |
When the server boots, the one starting the containers is Docker, a systemdThe first program Linux starts when it boots, process number 1. It starts the programs that must always be running (the services), restarts them if they crash and keeps what they write in a journal.Go to definition service since the introduction, not Compose: it starts them all at once, without waiting for the healthchecks. In our test, the three started within 10 milliseconds of each other, and by the time we logged back in, 18 seconds later, all three were healthy. migrate has no policy: it’s a task.
The secrets are generated on the server
Section titled “The secrets are generated on the server”You copy .env.production.example as .env on the server. Its two secrets:
# The secret the shop shares with the payment gateway to sign the webhooks. The server doesn't start# with this value, or with one under 32 characters. Generate it on the server and paste it here:# openssl rand -base64 32WEBHOOK_SECRET=change-this-to-a-secret-from-openssl-rand# The password of the database Compose creates. Empty, docker compose doesn't start. It goes inside# a URL, so only letters and numbers. Generate it on the server:# openssl rand -hex 24POSTGRES_PASSWORD=In Phase 5, PostgreSQL’s password was shop, and we promised you that on a server it would be long and secret. Now it’s 48 random characters:
- They’re generated on the server with
openssl rand, and never leave it: not through a chat, not through your laptop. They aren’t the development ones: if a production one leaks, your laptop’s are still safe, and the other way around. chmod 600 .env: only your user can read it, with the permissions from Phase 1.- Never in Git, as in Phase 6.
The other lines come in other lessons: TRUSTED_PROXY in lesson 4, ALLOWED_ORIGINS in 5, IMAGE in 6. Phase 6’s identity provider stays off: the practice one lives on your laptop.
# The identity provider (Phase 6, lesson 4): leave it like this and the shop works with email and# password. To offer "Sign in with Google" (or another provider), remove the # from the four lines:# either all four are there or none (an empty one makes the server not start). The callback URL# has to be https and on a domain of yours: Google doesn't accept an IP or sslip.io.# OIDC_ISSUER=https://accounts.google.com# OIDC_CLIENT_ID=the-id-google-gives-you# OIDC_CLIENT_SECRET=the-secret-google-gives-you# OIDC_REDIRECT_URI=https://shop.example/v2/session/provider/callbackLeave the four lines with their #. OIDC_ISSUER= with no value isn’t the same as not having it: the variable exists, empty, and the API refuses to start.
Logs: Docker doesn’t trim them
Section titled “Logs: Docker doesn’t trim them”Docker saves what the API writes in one file per container, with its default driver, json-file. According to Docker’s documentation, that file isn’t rotated: it grows with no limit. The installation from the introduction doesn’t change that: /etc/docker is left empty.
Do the math. The healthcheck asks /health every 10 seconds, and each question is a line of about 290 bytes. That’s 8,640 lines a day, about 2.5 MB: about 900 MB a year without a single visitor.
You fix it in /etc/docker/daemon.json, the engine’s configuration:
{ "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" }}At 10 MB, Docker starts another file, and it keeps three at most. It only applies to containers created afterwards: you have to recreate them. systemd’s journal, on the other hand, trims itself.
A copy every night
Section titled “A copy every night”A volume isn’t a copy, as you saw in Phase 7: it’s the only place your data lives. The BackupA copy of the data kept apart, to get it back if the original is lost or damaged. You only know it works if you have tried restoring it, and it does not save you from losing the disk if it lives on the same one.Go to definition is made by a script in the step:
# Only your user can read what's created here (permissions 600 on the files, 700 on the folder): a# backup is the whole database, with the emails, the password hashes and the sessions.umask 077
# The project's folder: this script's, one level up.cd "$(dirname "$0")/.."
days="${BACKUP_DAYS:-7}"mkdir -p backups# A folder created by another user (a sudo, say) can't be closed by this one: say how to fix it# instead of failing on chmod with a bare error.if [ ! -O backups ]; then echo "backups/ belongs to another user (did a sudo create it?): sudo chown -R \"\$(id -un)\": backups" >&2 exit 1fi# If the folder already existed with other permissions, it's closed too.chmod 700 backupsfinal="backups/shop-$(date +%Y-%m-%d-%H%M%S).sql.gz"
# The dump is written to a .tmp file, and only gets its real name if everything went well. If# something fails (the database stopped, the disk full), the trap deletes the .tmp: there's never a# half backup that looks good, and because of set -e the script stops before deleting the old ones.trap 'rm -f "$final.tmp"' EXIT
# pg_dump, inside the db container (-T: no terminal, so it can be chained), is compressed with gzip# outside. With pipefail, if pg_dump fails, the whole line fails, even if gzip ends well.docker compose -f compose.production.yaml exec -T db pg_dump -U shop shop | gzip > "$final.tmp"mv "$final.tmp" "$final"echo "Backup made: $final ($(du -h "$final" | cut -f1))"umask 077: whatever the script creates is born for your user only. A backup holds the emails and the password hashes.exec -T db pg_dump … | gzip: the dump, compressed.-Tmeans “no terminal,” so it can go through the pipe.- First
.tmp, thenmv:set -estops the script at the first failure, andtrap … EXITis what runs on the way out, whether things went well or badly: it deletes the.tmp. There’s never a half-made copy with the name of a good one.
# Only now, with a good new backup, are the ones that are $days days old or more deleted. find counts# whole days and rounds down: "-mtime +6" is "7 days or more" (+7 would let 8 days through).find backups -name 'shop-*.sql.gz' -mtime +"$((days - 1))" -print -delete# And the .tmp files that were left behind (a kill -9 doesn't let the trap act), from over an hour ago.find backups -name 'shop-*.sql.gz.tmp' -mmin +60 -print -deleteThe pruning deletes the ones 7 days old or more, and only after a good new copy: if the database is down, the script has already failed and the old ones stay.
A systemd timer launches it, with two files like the service from Phase 1:
# A backup of the database (shop-backup.timer launches it). Install it with:# sudo cp deployment/shop-backup.service deployment/shop-backup.timer /etc/systemd/system/# sudo systemctl daemon-reload && sudo systemctl enable --now shop-backup.timer# Change User and the two paths if your user or your folder aren't ubuntu and /opt/shop.[Unit]Description=Backup of the shop's database# Without Docker running there is no database to copy from.Requires=docker.serviceAfter=docker.service
[Service]# Type=oneshot: it does a task and ends (it isn't a server that stays).Type=oneshot# If it hangs (a dump that never ends), systemd cuts it after 30 minutes.TimeoutStartSec=30min# A user in the docker group, not root. Careful: the docker group is equivalent to root (whoever# can talk to Docker can mount any folder of the server in a container). It's used anyway because# that way the backups belong to ubuntu and not to root, and ubuntu is who already administers# Docker on this server.User=ubuntuWorkingDirectory=/opt/shopExecStart=/opt/shop/deployment/backup.sh# When the backup is made (Phase 1: a systemd timer is a cron with better logging).[Unit]Description=Nightly backup of the shop
[Timer]# Every night at 03:30, server time.OnCalendar=*-*-* 03:30:00# If the server was off at that time, it does it as soon as it starts.Persistent=true
[Install]WantedBy=timers.targetType=oneshot: a task that ends, not a server.User=ubuntu: your user, notroot. It can talk to Docker because it’s in thedockergroup, which is as good as root.OnCalendar=*-*-* 03:30:00: every day at 03:30.Persistent=true: if the server was off, it makes the copy when it boots.
A copy on the same disk doesn’t save you if you lose the disk. Take it somewhere else every now and then, for example from your computer: rsync -av ubuntu@192.168.5.15:/opt/shop/backups/ shop-backups/.
Try it
Section titled “Try it”The goal: the shop running on your server, coming back on its own after a reboot, with your admin account, logs with a limit and a copy restored into an empty database.
The outputs are from a VM with Ubuntu 26.04, Docker 29.9.1, Compose 5.6.0 and the IP 192.168.5.15: use your server’s. Your times, IDs, ports and passwords will be different. On a VPS, everything is the same.
The step, on the server
Section titled “The step, on the server”The shop will live in /opt/shop: /opt is the folder for programs that don’t come with the system, and the step’s systemd files expect it there. Since it belongs to root, you first copy the step to your folder on the server. On your computer:
1. Copy the step to the server
curl -O https://backenddesdecero.com/practicas/shop-api/35-production.tar.gztar -xzf 35-production.tar.gzrsync -av 35-production/ ubuntu@192.168.5.15:shop/curl.exe -O https://backenddesdecero.com/practicas/shop-api/35-production.tar.gztar -xzf 35-production.tar.gzscp -r 35-production ubuntu@192.168.5.15:shopWhat you will see:
Transfer starting: 143 filescreated directory shop./.dockerignore.env.example.env.production.example…sent 578767 bytes received 2974 bytes 36132981 bytes/sectotal size is 566278 speedup is 0.97It’s the rsync from Phase 1: look at created directory shop. On Linux, the first line is sending incremental file list. PowerShell doesn’t come with rsync, but it does have scp: scp -r copies the folder and, since shop doesn’t exist on the server, creates it with that name.
The download doesn’t include .env: your development .env must not reach the server. If you copy your own project, add --exclude node_modules --exclude .env.
Now, inside the server, move it to /opt and go into it. The folder is still yours: you don’t need sudo to work in it.
sudo mv shop /opt/cd /opt/shopThe .env, with new secrets
Section titled “The .env, with new secrets”2. A .env only you can read
cp .env.production.example .envchmod 600 .envls -l .envWhat you will see:
-rw------- 1 ubuntu ubuntu 2351 Oct 18 01:47 .envLook at -rw-------: read and write for ubuntu, nothing for anyone else. If you start it now, Compose refuses with required variable POSTGRES_PASSWORD is missing a value.
Generate the two secrets and write them into .env without them going through your screen:
sed -i "s|^WEBHOOK_SECRET=.*|WEBHOOK_SECRET=$(openssl rand -base64 32)|" .envsed -i "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=$(openssl rand -hex 24)|" .env$(openssl rand …): the terminal runs what’s inside and puts its output in its place.sed -i "s|A|B|": changes in the file (-i) whatever matchesAintoB.^WEBHOOK_SECRET=.*is the line that starts withWEBHOOK_SECRET=. The separator is|because base64 uses/.
.env is still 600. grep -c change-this .env should say 0: the example secret is gone.
Start the shop
Section titled “Start the shop”3. The shop, in production
docker compose -f compose.production.yaml up -d --buildWhat you will see:
…[+] up 7/7✔ Image shop-api Built 3.1s✔ Network shop_default Created 0.0s✔ Volume shop_data Created 0.0s✔ Container shop-redis-1 Healthy 3.4s✔ Container shop-db-1 Healthy 3.4s✔ Container shop-migrate-1 Exited 3.8s✔ Container shop-api-1 Started 3.9sAs in Phase 7, but everything is built on the server: the first time it takes a few minutes, and before this come the build steps, which we trimmed (…). If it stops with Killed, it’s short of memory: the VM needs the 2 GB from the introduction.
4. Does it answer?
docker compose -f compose.production.yaml ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"curl -s http://$(docker compose -f compose.production.yaml port api 3000)/health; echoWhat you will see:
NAME STATUS PORTSshop-api-1 Up 23 seconds (healthy) 127.0.0.1:3001->3000/tcpshop-db-1 Up 27 seconds (healthy) 5432/tcpshop-redis-1 Up 27 seconds (healthy) 6379/tcp{"status":"ok"}--format leaves three columns. Only the API has an arrow in PORTS, and it starts with 127.0.0.1. Ours got 3001, from the range; yours may be on 3000. That’s why curl asks docker compose port for the port. If you see (health: starting), wait a few seconds.
5. Who's listening, and as whom
ss -ltn | grep -E ":(3000|3001|5432|6379) "docker compose -f compose.production.yaml exec api whoamidocker compose -f compose.production.yaml exec api printenv HOSTWhat you will see:
LISTEN 0 4096 127.0.0.1:3001 0.0.0.0:*node0.0.0.0ss -ltn lists the ports listening on the server: of the shop’s, only the API’s, on 127.0.0.1. Inside the container, the API is node and listens on 0.0.0.0. From your computer, http://192.168.5.15:3001 doesn’t answer, and that’s how it should be.
Your admin account
Section titled “Your admin account”6. create-admin
docker compose -f compose.production.yaml run --rm api node scripts/create-admin.ts admin@shop.exampledocker compose -f compose.production.yaml exec db psql -U shop -c "SELECT id, email, role FROM users;"What you will see:
…Container shop-api-run-a8c42ca470dc CreatedAdmin account created: admin@shop.examplePassword (save it now, it is not shown again): 4i5QbeyYxzyO_6TIXLLd-Touid | email | role----+--------------------+-------1 | admin@shop.example | admin(1 row)Use your own email. run --rm api creates a container with the API’s image, runs the script and deletes it. The script generates a random password and saves only its HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition. Save it now in your password manager: it isn’t shown again. The query confirms it: a single account, yours.
Reboot the server
Section titled “Reboot the server”7. Off and on again
sudo reboot# … log back in over SSH, and:cd /opt/shopuptime -pdocker compose -f compose.production.yaml ps --format "table {{.Name}}\t{{.Status}}"curl -s http://$(docker compose -f compose.production.yaml port api 3000)/health; echoWhat you will see:
up 0 minutesNAME STATUSshop-api-1 Up 18 seconds (healthy)shop-db-1 Up 18 seconds (healthy)shop-redis-1 Up 18 seconds (healthy){"status":"ok"}sudo reboot kicks you out: wait half a minute and log back in. uptime -p says the server has just been turned on, and the shop is already healthy without you typing up. If it doesn’t show up, systemctl is-enabled docker should say enabled.
Put a limit on the logs
Section titled “Put a limit on the logs”docker compose -f compose.production.yaml logs api shows what the API has written; with -f, it waits for new lines. Look at its limits:
8. No limit
docker info --format "{{.LoggingDriver}}"docker inspect --format "{{json .HostConfig.LogConfig}}" shop-api-1What you will see:
json-file{"Type":"json-file","Config":{}}Config is empty: neither max-size nor max-file.
sudo tee writes, with root’s permissions, whatever reaches it up to the EOF line:
9. With a limit
sudo tee /etc/docker/daemon.json <<'EOF'{"log-driver": "json-file","log-opts": { "max-size": "10m", "max-file": "3"}}EOFsudo systemctl restart dockerdocker compose -f compose.production.yaml up -d --force-recreatedocker inspect --format "{{json .HostConfig.LogConfig}}" shop-api-1What you will see:
{"log-driver": "json-file","log-opts": { "max-size": "10m", "max-file": "3"}}…{"Type":"json-file","Config":{"max-file":"3","max-size":"10m"}}tee repeats what it writes. When Docker restarts, the shop comes back on its own, but with an empty Config until --force-recreate creates its containers again. The last line now has the limits. If Docker doesn’t start, the JSON has a mistake: sudo journalctl -u docker -n 20 tells you which.
The nightly copy
Section titled “The nightly copy”10. The timer
chmod +x deployment/backup.shsudo cp deployment/shop-backup.service deployment/shop-backup.timer /etc/systemd/system/sudo systemctl daemon-reloadsudo systemctl enable --now shop-backup.timersystemctl list-timers shop-backup.timerWhat you will see:
Created symlink '/etc/systemd/system/timers.target.wants/shop-backup.timer' → '/etc/systemd/system/shop-backup.timer'.NEXT LEFT LAST PASSED UNIT ACTIVATESSun 2026-10-18 03:30:00 CEST 1h 40min Sat 2026-10-17 18:20:27 CEST - shop-backup.timer shop-backup.service…chmod +x makes the script executable: the download doesn’t keep that permission, on any system. daemon-reload reads the new files, and enable --now turns the timer on now and at every boot. Look at NEXT: 03:30. LAST is the last copy; in ours, from earlier tests, and in yours, -. If your user or your folder are different, change User and the paths in the .service before copying it.
Don’t wait until 03:30:
11. A copy right now
sudo systemctl start shop-backup.servicejournalctl -u shop-backup.service -n 5 --no-pagerls -l backupsWhat you will see:
Oct 18 01:49:42 course systemd[1]: Starting shop-backup.service - Backup of the shop's database...Oct 18 01:49:42 course backup.sh[5079]: Backup made: backups/shop-2026-10-18-014942.sql.gz (4.0K)Oct 18 01:49:42 course systemd[1]: shop-backup.service: Deactivated successfully.Oct 18 01:49:42 course systemd[1]: Finished shop-backup.service - Backup of the shop's database.total 4-rw------- 1 ubuntu ubuntu 2764 Oct 18 01:49 shop-2026-10-18-014942.sql.gzLook at Backup made and at -rw-------: only ubuntu can read it. If you’ve run it before, the journal shows earlier lines too. If it says service "db" is not running, the shop is stopped: there’s no new copy and no .tmp, and the old ones are still there.
Restore the copy
Section titled “Restore the copy”A copy you’ve never restored is a hope. Try it in a new database, test, with your file’s name:
12. Restore
docker compose -f compose.production.yaml exec -T db createdb -U shop testgunzip -c backups/shop-2026-10-18-014942.sql.gz | docker compose -f compose.production.yaml exec -T db psql -U shop -d test -q -v ON_ERROR_STOP=1What you will see:
…setval-------- 1(1 row)createdb creates the empty database, gunzip -c decompresses the copy and psql runs it in test. ON_ERROR_STOP=1 stops at the first error instead of leaving it half done. The last setval puts the id counter back where it was.
13. Is everything there?
for db in shop test; do echo "== $db"; docker compose -f compose.production.yaml exec -T db psql -U shop -d $db -tc "select (select count(*) from products) as products, (select count(*) from users) as users, (select count(*) from orders) as orders"; donedocker compose -f compose.production.yaml exec -T db dropdb -U shop testWhat you will see:
== shop 4 | 1 | 25
== test 4 | 1 | 25Products, users and orders in both: the same numbers. The 4 products and the 25 orders are the sample ones, and the user is your account. dropdb deletes test.
Now, the real way back. Imagine a mistake deletes the shop’s accounts. With the API stopped, you delete the database, create it empty, load the copy and start the API. Only do it with a copy you’ve just tested:
14. Back to the copy
docker compose -f compose.production.yaml exec -T db psql -U shop -c "DELETE FROM users;"docker compose -f compose.production.yaml stop apidocker compose -f compose.production.yaml exec -T db dropdb -U shop shopdocker compose -f compose.production.yaml exec -T db createdb -U shop shopgunzip -c backups/shop-2026-10-18-014942.sql.gz | docker compose -f compose.production.yaml exec -T db psql -U shop -d shop -q -v ON_ERROR_STOP=1 > /dev/nulldocker compose -f compose.production.yaml start apidocker compose -f compose.production.yaml exec db psql -U shop -c "SELECT id, email, role FROM users;"What you will see:
DELETE 1Container shop-api-1 StoppingContainer shop-api-1 Stopped…Container shop-api-1 Startedid | email | role----+--------------------+-------1 | admin@shop.example | admin(1 row)DELETE 1 is the disaster. dropdb can’t delete a database with open connections: that’s why the API is stopped first. > /dev/null throws away psql’s results, which you already saw in test. At the end, your account is back. If what you lost is newer than the copy, that doesn’t come back: the copy is from last night.
The shop stays running: lesson 4 puts nginx in front of it.
You have already seen it
Section titled “You have already seen it”- Your home router. After a power cut, it gives you wifi again without you doing anything: its policy is “always.”
- WhatsApp backups. They happen on their own every day, if you choose so, and they go to iCloud or Google Drive, not to the phone: if you lose it, the copy is still there.
- Time Machine, on the Mac. It keeps hourly copies for the last day, daily copies for the last month and weekly copies before that: it deletes the old ones, like the 7-day pruning.
Common mistakes
Section titled “Common mistakes”docker compose upwithout-fon the server. It starts the developmentcompose.yaml, with the same volume: it loads the practice accounts, with two admins whose password is public, and it doesn’t come back after a reboot. You don’t need it on the server: afterrm compose.yaml, Compose will sayno configuration file provided: not found.- Copying your development
.env, or pushing it to Git. The same secret lives in two places, andlocalhostand your laptop’s provider get mixed up with production. - An
OIDC_line with no#and no value. The API doesn’t start:OIDC_ISSUER is not a URL. - Copies that never leave the server, or that you’ve never restored. If the disk dies, they go with it; if they don’t restore, you find out on the worst possible day.
down -vin production. It deletes the volume with all the orders. To stop, plaindown.
Summary
Section titled “Summary”compose.production.yamlis the server’s shop:restart: unless-stopped, the API only on127.0.0.1, PostgreSQL and Redis with no ports and no practice accounts.- The secrets are generated on the server, in a
.envwith600permissions that never goes to Git. - With
unless-stopped, Docker starts the shop again if it crashes and when the server boots, except what you stopped yourself. json-filedoesn’t trim the logs:max-sizeandmax-fileindaemon.json, and recreated containers.- A systemd timer runs a
pg_dumpevery night and keeps 7 days. A copy is worth what its last restore was worth, and it’s better off the server.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Start containers automatically, from Docker’s documentation: restart policies.
- JSON File logging driver:
max-size,max-fileand why it doesn’t rotate by default. - Use Compose in production: what changes from a development file to a production one.
- SQL Dump, from PostgreSQL’s documentation:
pg_dumpand how to restore. - systemd.timer:
OnCalendar,Persistentand the rest.