15 min read
Docker volumes vs bind mounts: data that lasts
In one sentence: A volume is a folder Docker keeps outside the containers and mounts inside them: what's written there survives when you delete the container. A bind mount puts a folder from your computer into the container. Volumes are for data, like PostgreSQL's; bind mounts, for your code while you develop.
What you will learn
- Create, list, inspect and delete volumes, and mount them with -v.
- Run PostgreSQL 18 in a container with its volume, and check that the data survives docker rm.
- Develop with a bind mount, with node --watch seeing your changes, and know what happens to node_modules.
- Back up the database with pg_dump through docker exec, and explain why not by copying the volume.
Before you start, read: 04-multi-stage.md
The problem
Section titled “The problem”Picture Ana starting PostgreSQL in a ContainerA program that runs isolated and carries inside everything it needs, with its own files, its own network and its own processes. It isn’t a virtual machine, because it doesn’t start a whole system; it shares the Linux kernel of the machine it runs on. That’s why it starts in less than a second.Go to definition, like the nginx from lesson 1. She loads the products, creates her account and tries the shop for a week. One day she wants to change the port: she deletes the container with docker rm -f and creates it again with the new port.
PostgreSQL starts empty, and the API fails with relation "products" does not exist: the table doesn’t exist.
It’s what you saw with nginx’s home page: what a container writes goes away with it. A database needs to keep its files somewhere that doesn’t depend on the container.
The analogy
Section titled “The analogy”The analogy
Think of a furnished rental apartment. When you leave, the owner puts it back the way it was for the next tenant: your things disappear.
So you don’t lose your things, you rent a storage unit on the side. You move to another apartment and the storage unit is still there, with your key.
There’s another way: a door in the apartment that opens onto a room in your own house. What you leave there, you see from both sides.
The apartment is the container; the storage unit, a volume; and the door to your house, a bind mount.
Where the analogy breaks down
- On a Mac or on Windows, a volume lives inside Docker’s virtual machine, not among your usual folders.
- Two apartments can share a storage unit. Two PostgreSQL servers writing the same files at the same time ruin the database.
- The storage unit isn’t a copy: if you empty it (
docker volume rm), you lose everything.
How it really works
Section titled “How it really works”Two ways to keep things outside the container
Section titled “Two ways to keep things outside the container”A container writes to its own layer, on top of the image’s (lesson 1). docker stop keeps it; docker rm deletes it.
For something to survive, Docker mounts a folder from outside at a path in the container. There are two kinds:
| Volume (in Docker)A folder Docker keeps outside the containers and mounts inside the ones that ask for it. What’s written to it survives when the container is deleted, so that’s where the data you need to keep goes, like a database’s.Go to definition | Bind mountA folder on your computer that shows up inside a container. Both see the same files at the same time, without copying them, so what you save in your editor is read by the container right away. It’s used mostly for development.Go to definition | |
|---|---|---|
| What it is | A folder Docker creates and keeps | A folder of yours, whichever you choose |
| How you write it | -v data:/var/lib/postgresql |
-v "$PWD":/app |
| Where it lives | Inside Docker (on a Mac and Windows, in its virtual machine) | On your disk, where it already was |
| What for | Data: a database, uploaded files | Your code while you develop |
Docker tells them apart by what comes before the colon: a name is a volume; a path, which starts with / or ., is a folder of yours. After the colon always comes the path inside the container.
A volume: a folder Docker manages
Section titled “A volume: a folder Docker manages”Volumes have their own family of commands, docker volume:
| Command | What it does |
|---|---|
docker volume create data |
Creates an empty volume called data |
docker volume ls |
Lists the volumes |
docker volume inspect data |
Shows its details, among them where Docker keeps the files |
docker volume rm data |
Deletes it, with everything in it. It refuses if any container, even a stopped one, uses it |
You don’t need to create it first: if -v data:/path names a volume that doesn’t exist, docker run creates it. And deleting the container doesn’t delete the volume: if you don’t need it, you delete it yourself.
A bind mount: a folder from your computer
Section titled “A bind mount: a folder from your computer”With -v "$PWD":/app, the folder you’re in shows up at /app inside the container. $PWD is the variable with your current folder, the one pwd writes; the quotes protect it if its name has spaces.
Nothing gets copied: both see the same files. What you save in your editor, the container reads right away, and what the container writes shows up on your disk. If /app already had something in the image, the bind mount covers it for as long as it lasts.
That’s what it’s for: developing in a container with Node 26, with node --watch restarting the server every time you save.
On a Mac, a bind mount is slower: every read crosses from macOS to Docker’s virtual machine. On our Mac, reading the more than 7,000 files in the shop’s node_modules took 2.1 seconds from a bind mount and 0.1 from a volume. On Linux there’s nothing to cross, and neither is there on WSL with the project in your Linux folder (~).
Where PostgreSQL 18 keeps its data
Section titled “Where PostgreSQL 18 keeps its data”Each Docker imageA read-only template with the files a program needs (the program itself, its libraries and a minimal system) and the command to start it. You can start as many containers as you want from one image, and none of them changes it.Go to definition decides where its program writes, and the volume has to go right there. In the postgres:18 image, the volume goes at /var/lib/postgresql. Inside, PostgreSQL creates its folder with the version number, 18/docker. The image’s documentation says so, and it changed in 18: up to 17 it went at /var/lib/postgresql/data, the path you’ll see in almost every tutorial.
The image knows that folder is for data: it declares a volume there. If you start PostgreSQL without -v, Docker creates an anonymous volume, with a name of 64 random letters and numbers, like the ones you may see in your docker volume ls. A new container doesn’t reuse it: it creates another one, empty. That’s what happened to Ana.
The variables POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB are only used when the volume is empty: they create the user and its database, which stay saved in it.
Port 5432 may be taken
Section titled “Port 5432 may be taken”Your PostgreSQL from Phase 5 listens on PortA number, from 0 to 65535, that says which program on a computer a connection is for. The computer has an address; each listening program has its port.Go to definition 5432 of your computer. If you publish the container on the same one, Docker can’t use it. You have two ways out:
- Stop yours: on a Mac,
brew services stop postgresql@18; on Ubuntu and WSL,sudo pg_ctlcluster 18 main stop. You start it again withstart. That way you can publish on127.0.0.1:5432. - 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 on another port:
-p 127.0.0.1:5433:5432. Outside, 5433; inside, PostgreSQL stays on its 5432. Both live side by side, and it’s what this lesson does.
Backups with pg_dump
Section titled “Backups with pg_dump”A volume isn’t a backup: it’s the only place your data is. The backup is made with pg_dump, the PostgreSQL program that writes a whole database as SQL commands, like the ones in shop.sql. The image includes it, and you run it inside with docker exec.
And copying the volume’s folder? Not with PostgreSQL running. Its files change while you copy them: you’d take some from before a change and others from after it, a copy that might not start. pg_dump reads everything from a single TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition, a consistent snapshot, while the shop keeps serving. Copying the files is only safe with the container stopped.
Try it
Section titled “Try it”The goal: PostgreSQL in a container, with the shop’s data, which survives deleting the container; then, your code in a container that sees your changes; and a backup of the database.
You work in ~/backend-course/phase-3/shop-api, with the project from lesson 4. The outputs are from Docker Engine 29 on a Mac, inside a virtual machine running Linux, like Docker Desktop’s. We captured them with other ports and names, swapped for the lesson’s: nothing else changes. Your IDs, dates and times will be different.
1. Create the volume
docker volume create datadocker volume lsWhat you will see:
dataDRIVER VOLUME NAMElocal datacreate answers with the name. DRIVER local: the files go to the disk of the machine where Docker runs. We’ve removed our other volumes; yours would show up too.
2. See where Docker keeps it
docker volume inspect dataWhat you will see:
[ { "CreatedAt": "2026-10-14T07:46:39+02:00", "Driver": "local", "Labels": null, "Mountpoint": "/var/lib/docker/volumes/data/_data", "Name": "data", "Options": null, "Scope": "local" }]Mountpoint is the real folder. On Linux it’s on your disk, and only root can read it. On a Mac and on Windows, inside Docker’s virtual machine.
Now, PostgreSQL. Choose a password for the shop user and put it where it says YOUR-PASSWORD: openssl rand -hex 24 gives you one that fits in a URL (lesson 7 tells you why). Keep it for lesson 6.
3. PostgreSQL 18 with its volume
docker run -d --name db \ -v data:/var/lib/postgresql \ -e POSTGRES_USER=shop -e POSTGRES_PASSWORD=YOUR-PASSWORD -e POSTGRES_DB=shop \ -p 127.0.0.1:5433:5432 \ postgres:18@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336What you will see:
1bf81649d836e0ec2f13ddf1c94eba4c0dcbe2e0e315f5ac0e93fd8c85f20b76Word by word:
--name db: the container’s name, the same one lesson 6 will use. The\at the end of a line continues the command on the next one.-v data:/var/lib/postgresql: mounts thedatavolume where PostgreSQL 18 keeps its files.-e POSTGRES_USER=shop,POSTGRES_PASSWORDandPOSTGRES_DB=shop: the user, its password and its database, which are created this first time.-p 127.0.0.1:5433:5432: the container’s 5432, on your computer’s 5433 and only for you.postgres:18@sha256:…: the image pinned by 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, like theFROMin lesson 3: the same PostgreSQL 18.6 as ours. Lesson 8 tells you why the course pins images this way.
If you get address already in use, port 5433 is taken: see “Common mistakes.”
4. What it did the first time
docker logs dbWhat you will see:
The files belonging to this database system will be owned by user "postgres".…fixing permissions on existing directory /var/lib/postgresql/18/docker ... ok…CREATE DATABASE…PostgreSQL init process complete; ready for start up.…2026-10-14 05:46:45.997 UTC [1] LOG: database system is ready to accept connectionsWe’ve trimmed the output (…). Look at /var/lib/postgresql/18/docker, the version’s folder inside the volume, and at the last line: it’s already accepting connections. If it isn’t there yet, wait a few seconds.
The database is empty. Fill it with your project’s MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition and data, as in Phase 5, with Node on your computer. Only the address changes, DATABASE_URL, which points to 5433 with your new password. So you don’t touch your .env, put it in an environment variable of your terminal for the time being:
5. The shop's tables and data
export DATABASE_URL=postgres://shop:YOUR-PASSWORD@localhost:5433/shopnpm run db:migrate && npm run db:seedunset DATABASE_URLWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 001-shop.sqlApplied: 002-stock.sqlApplied: 003-orders-index.sqlApplied: 004-categories-index.sqlApplied: 005-users.sqlApplied: 006-sessions.sqlApplied: 007-api-keys.sqlApplied: 008-provider.sqlApplied: 009-roles.sqlApplied: 010-notifications.sql
> shop-api@1.0.0 db:seed> node --env-file-if-exists=.env scripts/seed.ts
Practice accounts ready (their passwords are in the README)Sample data loadedexport leaves the variable in your terminal for both commands, and unset removes it at the end. node --env-file-if-exists doesn’t overwrite a variable that already exists: yours wins, not the one in .env.
If you get password authentication failed, check the password; if you get ECONNREFUSED, the port.
6. A product that only exists here
docker exec db psql -U shop -c "INSERT INTO products (name, price_cents, stock) VALUES ('Sticker', 300, 100);"What you will see:
INSERT 0 1docker exec db psql runs psql inside the container: you don’t need yours. -U shop logs in as that user, with no password, because the image trusts connections from inside. Without -d, it opens the database with the same name as the user.
7. Delete the container and create another
docker rm -f dbdocker run -d --name db \ -v data:/var/lib/postgresql \ -e POSTGRES_USER=shop -e POSTGRES_PASSWORD=YOUR-PASSWORD -e POSTGRES_DB=shop \ -p 127.0.0.1:5433:5432 \ postgres:18@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336docker logs dbWhat you will see:
dbac5d38e959c38bcf80138a30d13a8f969cb79576c4bb2ae480276eb79eecb639
PostgreSQL Database directory appears to contain a database; Skipping initialization…2026-10-14 05:47:00.747 UTC [32] LOG: database system was not properly shut down; automatic recovery in progress…2026-10-14 05:47:00.780 UTC [1] LOG: database system is ready to accept connectionsA new container, with another ID, on the same volume. Two lines matter:
Skipping initialization: the volume already has a database, so the image creates nothing and doesn’t read thePOSTGRES_…variables.not properly shut down; automatic recovery:docker rm -fkilled PostgreSQL without letting it finish, and when it started it went over its journal, the WAL from the transactions lesson. The right way isdocker stop dband thendocker rm db.
8. Is the sticker still there?
docker exec db psql -U shop -c 'SELECT id, name, stock FROM products ORDER BY id;'What you will see:
id | name | stock----+---------+-------1 | T-shirt | 402 | Mug | 603 | Hoodie | 254 | Cap | 155 | Sticker | 100(5 rows)The four products from db:seed and your sticker: the data was in the volume, not in the container. If you get relation "products" does not exist, the -v in step 7 isn’t the same as the one in step 3.
Challenge: with db running, try to delete the volume with docker volume rm data. What happens, and why is it good news?Show answer
Error response from daemon: remove data: volume is in use - [ac5d38e959c38bcf80138a30d13a8f969cb79576c4bb2ae480276eb79eecb639]Docker refuses while there’s a container using it, and tells you which one, by its ID. To delete the data you have to delete the container first: two steps, hard to do by accident.
Your code, in a bind mount
Section titled “Your code, in a bind mount”Now, the API in a node:26 container that reads your folder. If you still have the shop container from lesson 4, delete it (docker rm -f shop): it uses the same port.
9. npm run dev, inside a container
docker run --rm -it --name shop-dev -v "$PWD":/app -w /app \ -e HOST=0.0.0.0 -p 127.0.0.1:3000:3000 node:26 npm run devWhat you will see:
> shop-api@1.0.0 dev> node --env-file-if-exists=.env --watch src/server.ts
{"level":30,"time":1791956837427,"pid":26,"hostname":"c67501ea2818","msg":"The shop is listening on http://localhost:3000"}-v "$PWD":/app: your project, with your.envand yournode_modules, at/app.-w /app(workdir): the folder where the command starts, likeWORKDIR.-e HOST=0.0.0.0: the server listens on every address of the container, as in lesson 3.node:26 npm run dev: the Node 26 image and the command, which startsnode --watch(Phase 3).
The terminal stays with the server: open another one.
Open src/app.ts in your editor and, in the / route, change "API for Ana and Luis's shop" to "Ana and Luis's shop, with a bind mount". Save. In the first terminal, node --watch clears the screen and restarts:
10. Your change, inside the container
curl -s localhost:3000/What you will see:
{"name":"Ana and Luis's shop, with a bind mount","versions":[{"version":"v2","url":"/v2","status":"current"},{"version":"v1","url":"/v1","status":"deprecated","sunset":"2027-04-13T00:00:00.000Z"}]}In the first terminal you’ll have seen:
Change detected in '/app/src/app.ts'Restarting 'src/server.ts'{"level":30,…,"msg":"SIGTERM: the shop is shutting down"}{"level":30,…,"msg":"The shop is listening on http://localhost:3000"}You edited on your computer and the container saw it, without rebuilding the image. If it doesn’t restart, see “Common mistakes.” Undo the change and stop the server with Ctrl + C: --rm deletes the container.
/health will answer 503: your .env says localhost:5432, and inside the container localhost is the container itself. Lesson 6 explains it and fixes it.
And whose node_modules is it?
Section titled “And whose node_modules is it?”With the bind mount, the container uses your node_modules, the one npm ci installed on your computer. Almost all the shop’s packages are JavaScript, which works on any system: that’s why npm run dev starts. But the TypeScript 7 compiler is a program compiled for your system, and from a Mac it fails inside:
11. A package compiled for another system
docker run --rm -v "$PWD":/app -w /app node:26 npm run checkWhat you will see:
> shop-api@1.0.0 check> tsc --noEmit
…Error: Unable to resolve @typescript/typescript-linux-arm64. Either your platform is unsupported, or you are missing the package on disk.…npm ci installed the macOS tsc on your Mac, and the container is Linux. On a Mac with Intel, the name ends in linux-x64. On Linux and WSL, it works: your node_modules is already Linux’s.
The way out: give the container its own node_modules, in a volume mounted on top of that folder. It covers yours only inside the container:
12. A node_modules just for the container
docker run --rm -v "$PWD":/app -v shop-modules:/app/node_modules -w /app \ node:26 sh -c 'npm ci && npm run check'What you will see:
added 74 packages, and audited 75 packages in 3s…> shop-api@1.0.0 check> tsc --noEmittsc writes nothing: the types are fine. npm ci installed for Linux in the shop-modules volume, and your node_modules stays the same. We’ve removed npm’s warnings.
A backup of the database
Section titled “A backup of the database”13. pg_dump, with the shop running
docker exec db pg_dump -U shop shop > shop-backup.sqlls -lh shop-backup.sqlgrep Sticker shop-backup.sqlWhat you will see:
-rw-r--r--@ 1 ana staff 15K Oct 14 07:47 shop-backup.sql5 Sticker 300 100pg_dump writes to its stdoutStandard output, the channel through which a program writes its results. Unless you say otherwise, it goes to the screen; it can be sent to a file or to another program.Go to definition, and your terminal’s > saves it in your folder (Phase 1). Inside there’s SQL with the tables, their data and your sticker. We’ve changed our user to ana. Don’t upload it to Git: it has the shop’s accounts.
To restore it into an empty database: docker exec -i db psql -U shop -d shop < shop-backup.sql. With -i, the container reads the file through its stdinStandard input, the channel through which a program receives data. Unless you say otherwise, it’s what you type; with a pipe, it’s what the previous program writes.Go to definition.
To finish, clean up. The data volume stays, with your data: lesson 6 uses it.
docker stop db && docker rm dbdocker volume rm shop-modulesYou have already seen it
Section titled “You have already seen it”- Your PostgreSQL from Phase 5. Homebrew keeps its data in
/opt/homebrew/var/postgresql@18, apart from the program: you update it without losing your data. A volume does the same for a container. - Phone apps. When they update, the whole program is replaced, and your data is still there, kept apart.
npm run devfrom Phase 3. The samenode --watch, now inside a container.
Common mistakes
Section titled “Common mistakes”- Mounting at
/var/lib/postgresql/datawith PostgreSQL 18. It’s the tutorials’ path up to 17. The container stops, anddocker logssaysError: in 18+, these Docker images are configured to store database data in a format…and suggests mounting at/var/lib/postgresql. -v data:…versus-v ./data:…. With a name, a volume. With./, thedatafolder wherever you are: if it doesn’t exist, Docker creates it, and PostgreSQL writes to your disk, slower on a Mac.- The port is taken. On Linux, Docker says
failed to bind host port 127.0.0.1:5432/tcp: address already in use; with Docker Desktop, an error that also ends inaddress already in use. Stop your PostgreSQL or use127.0.0.1:5433, and delete the container left inCreated(docker ps -a) before trying again. - The container doesn’t see your changes. Docker Desktop and Linux tell the container about every file you save; some alternatives don’t: with Colima, start it with
colima start --mount-inotify. On WSL, the project has to be in your Linux folder (~), not in/mnt/c. docker volume rm,docker volume prune -aordocker compose down -vwithout thinking. They delete the data, with no trash can. Make a backup withpg_dumpfirst.
Summary
Section titled “Summary”- A container’s layer goes away with
docker rm; what must survive goes in a volume (docker volume create,ls,inspect,rm). -v name:/pathmounts a volume, for data;-v "$PWD":/path, a folder of yours, for your code while you develop.- PostgreSQL 18 keeps its data at
/var/lib/postgresql, and a new container on the same volume finds it all. - If your native PostgreSQL takes 5432, stop it or publish the container on another port, like
127.0.0.1:5433. - Backups, with
pg_dumpthroughdocker exec: a consistent snapshot, without stopping the database.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Volumes, from Docker’s documentation: when to use them, anonymous ones and how to back them up.
- Bind mounts: when to use them and what happens when you mount on top of a folder with files.
- The official PostgreSQL image: its variables and the data path since 18.
- pg_dump, from PostgreSQL’s documentation: all its options.