Docker volumes and networking
A container on its own is a sealed box: its files vanish when it is removed, and only containers on a shared network can reach it. Volumes and networks are how you connect that box to the outside world deliberately. This page covers where container data can live, how to choose between volumes, bind mounts and tmpfs, and how containers find and talk to each other and to the host.
The examples use the invented OrdersPortal application: an orders-api container, a PostgreSQL 18 database and a Redis cache. No Docker daemon was available while writing this page, so commands are not run here; they follow the storage and networking guides on docs.docker.com. Compose snippets on this page were validated with docker compose config (Docker Compose 5.6), which parses and normalizes a file without a daemon.
Topics on this page
Section titled “Topics on this page”| Topic | What it answers |
|---|---|
| Storage options | The three mount types and when each fits. |
| Volumes | Creating, using, sharing and pruning Docker-managed volumes. |
| Bind mounts and tmpfs | Mounting host paths for development, and memory-only mounts. |
| Backing up volumes | A safe backup and restore pattern. |
| Network drivers | Bridge, host, none, overlay, macvlan and ipvlan. |
| User-defined networks and DNS | Name resolution between containers and network isolation. |
| Publishing ports | Making a container reachable from the host and beyond, safely. |
Storage options
Section titled “Storage options”Everything a container writes goes, by default, into its writable layer, which is deleted with the container and is slow for heavy writes. Docker offers three mount types to put data somewhere else:
| Type | Where data lives | Typical use |
|---|---|---|
| Volume | In storage managed by Docker (under Docker’s data directory on Linux) | Databases, uploads, anything that must outlive the container |
| Bind mount | A file or directory on the host, at a path you choose | Source code during development, host configuration files |
| tmpfs mount | Host memory only, Linux hosts | Scratch files and secrets that must never touch disk |
Use --mount for clarity in scripts (--mount type=volume,source=orders-data,target=/var/lib/postgresql); the shorter -v source:target syntax is equivalent for volumes and bind mounts. One behavioral difference: with -v, a missing host path for a bind mount is created as a directory, while --mount reports an error, which catches typos.
Pitfalls:
- No mount for stateful containers. The database looks fine until the container is recreated and the data is gone.
- Mounting the wrong path. Image authors document where data lives; mount exactly that path.
Volumes
Section titled “Volumes”Volumes are the preferred way to persist container data. Docker creates and manages them, they work the same on Linux, macOS and Windows hosts, they can be backed up and moved with Docker commands, and volume drivers can store them on NFS or other remote storage.
The PostgreSQL 18 image changed where data lives: PGDATA is now version-specific (/var/lib/postgresql/18/docker) and the image’s declared volume moved to /var/lib/postgresql. Mount the volume there. Mounting at the old /var/lib/postgresql/data path, which many older tutorials show, does not capture the database files with version 18 images.
# Not run heredocker volume create orders-datadocker run -d --name orders-db \ --mount type=volume,source=orders-data,target=/var/lib/postgresql \ -e POSTGRES_DB=orders -e POSTGRES_USER=orders_app -e POSTGRES_PASSWORD=change-me \ postgres:18-alpine
docker volume lsdocker volume inspect orders-dataIn Compose, declare named volumes at the top level and reference them in services. docker compose down keeps named volumes; docker compose down -v deletes them along with their data.
services: db: image: postgres:18-alpine volumes: - orders-data:/var/lib/postgresql
volumes: orders-data:Several containers can mount the same volume, for example an API writing uploaded invoices and a worker processing them. Docker does not coordinate their writes; the applications must handle concurrency, and only one database server may ever use a given data volume.
An anonymous volume is created when an image declares VOLUME and you do not mount anything there, or with -v /path without a name. It gets a random name and is easy to lose track of. docker volume prune removes only unused anonymous volumes by default; docker volume prune --all also removes unused named volumes, which deletes their data.
Pitfalls:
docker compose down -vas a habit. It deletes the development database too. Use it only when you mean to reset data.- Two database containers on one data volume. This corrupts data. One volume per database instance.
Bind mounts and tmpfs
Section titled “Bind mounts and tmpfs”A bind mount maps a host path into the container. Its main use is development: mount the source tree so changes on the host are visible in the container immediately, without rebuilding.
services: web: build: . command: npm run dev volumes: - ./src:/app/src # host source into the container - ./config/web.json:/app/config/web.json:roBind mounts depend on the host’s directory layout, so they make containers less portable, and the container can modify host files (add :ro or readonly when it should not). On Docker Desktop, bind mounts cross the VM boundary and are slower than volumes for heavy I/O; mounting a whole project including node_modules is a common cause of slow development environments. Compose’s file watch feature (develop.watch with action: sync) is an alternative that copies changed files into the container instead of mounting.
A tmpfs mount lives only in memory and disappears when the container stops. Use it for scratch space in a read-only container:
# Not run heredocker run -d --read-only --tmpfs /tmp \ --mount type=volume,source=orders-logs,target=/app/logs \ registry.example.test/ordersportal/orders-api:2.4.1--read-only makes the container’s root file system read-only, so the only writable paths are the ones you mount. Note that -v /tmp would create an anonymous volume on disk, not a tmpfs mount; use --tmpfs or --mount type=tmpfs.
Pitfalls:
- A bind mount hiding image content. Mounting over
/apphides everything the image put there, including dependencies installed at build time. - File ownership mismatches. A non-root container user may not be able to write to a host directory owned by your user ID. Align UIDs or use a volume.
Backing up volumes
Section titled “Backing up volumes”Because a volume is managed by Docker, the portable way to back it up is to run a short-lived container that mounts both the volume and a host directory, and archive one into the other:
# Not run here: stop the database first, or use pg_dump for a consistent backupdocker run --rm \ --mount type=volume,source=orders-data,target=/source,readonly \ --mount type=bind,source="$(pwd)",target=/backup \ alpine tar czf /backup/orders-data.tar.gz -C /source .
# Restore into a new, empty volumedocker volume create orders-data-restoreddocker run --rm \ --mount type=volume,source=orders-data-restored,target=/target \ --mount type=bind,source="$(pwd)",target=/backup,readonly \ alpine tar xzf /backup/orders-data.tar.gz -C /targetA file-level copy of a running database can be inconsistent. For databases, prefer the database’s own tools (pg_dump, pg_basebackup), and use file-level volume backups for stopped containers or simple file stores.
Pitfalls:
- Backups never restored. Test restores on a schedule; a backup you have not restored is a hope.
- Backing up to the same disk. Copy archives off the host.
Network drivers
Section titled “Network drivers”Docker networking is pluggable through drivers:
- bridge (default): a private software network on one host. Containers get private IPs and reach the outside world through NAT.
- host: the container shares the host’s network stack. No isolation and no port mapping; the process binds host ports directly. Native on Linux, and supported on Docker Desktop 4.34 and later when the feature is enabled.
- none: no networking at all, apart from loopback.
- overlay: spans several Docker hosts, used by Swarm services.
- macvlan and ipvlan: give containers addresses on the physical network, for workloads that must appear as devices on the LAN.
Most applications need only bridge networks, and specifically user-defined ones.
Pitfalls:
- Host networking for convenience. It removes isolation and causes port conflicts. Use it only for measured performance needs or tools that must see host interfaces.
- Overlapping subnets. Docker’s default bridge ranges can collide with VPN or office networks; configure
default-address-poolsin the daemon settings if they do.
User-defined networks and DNS
Section titled “User-defined networks and DNS”Containers not attached to any network you name join the default bridge network. On the default bridge, containers can reach each other only by IP address, and every unrelated container on the host shares it. A user-defined bridge network fixes both: containers on it resolve each other by container name (and network alias) through Docker’s embedded DNS server at 127.0.0.11, and only containers you attach can talk to each other.
# Not run heredocker network create orders-backenddocker run -d --name orders-db --network orders-backend postgres:18-alpinedocker run -d --name orders-api --network orders-backend \ -e ConnectionStrings__Orders="Host=orders-db;Database=orders;Username=orders_app" \ registry.example.test/ordersportal/orders-api:2.4.1Compose creates a network for each project automatically, and every service can reach every other service by its service name, so Host=db works with no configuration. Define extra networks when you want to separate tiers. An internal: true network has no route to the outside world, which suits a database and cache that should talk only to the API:
services: api: networks: [frontend, backend] db: image: postgres:18-alpine networks: [backend] # unreachable from frontend-only services
networks: frontend: backend: internal: trueA container can be attached to several networks, which is how a reverse proxy or API bridges tiers. docker network inspect <name> shows which containers are attached and their addresses, and docker network connect and disconnect change attachments at run time.
Pitfalls:
- Relying on the default bridge. Name resolution does not work there, and links (
--link) are a legacy feature. Create a network. - Using
localhostto reach another container. Inside a container,localhostis that container. Use the other container’s name.
Publishing ports
Section titled “Publishing ports”Containers on a bridge network are not reachable from outside the host until you publish a port: -p 8080:8080 maps host port 8080 to container port 8080, and -P publishes every EXPOSEd port on random host ports. docker port <container> shows the mappings.
By default, -p 8080:8080 listens on all host interfaces, which makes the service reachable from the network, not just from your machine. For local development or for services behind a reverse proxy on the same host, bind to loopback: -p 127.0.0.1:8080:8080. On Linux, Docker manages firewall rules for published ports itself, and those rules take effect before many host firewall configurations, so a port you thought a host firewall blocked may still be open.
In production on a single host, publish only the reverse proxy (ports 80 and 443) and keep application and database containers unpublished on internal networks; the proxy reaches them by name. To reach a service running on the host from a container, Docker Desktop provides the name host.docker.internal; on Linux Engine, add --add-host=host.docker.internal:host-gateway.
Pitfalls:
- Publishing database ports on servers.
-p 5432:5432on an internet-facing host exposes the database. Do not publish it, or bind it to 127.0.0.1. - Port conflicts when scaling. Two containers cannot publish the same host port; put a proxy in front instead.
Choosing between them
Section titled “Choosing between them”| Need | Use |
|---|---|
| Database or upload data that must survive container recreation | Named volume |
| Live-edited source code in development | Bind mount or Compose file watch |
| Scratch space or in-memory secrets | tmpfs mount, often with --read-only |
| Containers that talk to each other by name | User-defined bridge network (or Compose’s default network) |
| A tier with no internet access | Network with internal: true |
| A service reachable only from this machine | -p 127.0.0.1:host:container |
| Multi-host networking | Kubernetes or Swarm overlay networking |
Interview questions
Section titled “Interview questions”What is the difference between a volume and a bind mount? A volume is created and managed by Docker in its own storage area and is portable across hosts and platforms. A bind mount maps an arbitrary host path into the container, so it depends on the host’s directory layout and exposes host files to the container.
Why can’t two containers on the default bridge network reach each other by name? The default bridge does not provide automatic DNS between containers. User-defined networks use Docker’s embedded DNS server so containers resolve each other by name.
A container’s localhost:5432 cannot reach the database container. Why?
localhost refers to the container’s own network namespace. Put both containers on the same user-defined network and connect to the database container’s name.
What does internal: true do on a Compose network?
It creates a network without external connectivity: containers on it can talk to each other but have no route to the outside world.
Senior scenario: after recreating OrdersPortal’s database container, the development database is empty, and a security scan finds Redis reachable from the office network. What went wrong and how do you fix it?
The database was probably writing into its container layer or an anonymous volume, often because the volume was mounted at /var/lib/postgresql/data, which PostgreSQL 18 images no longer use. Mount a named volume at /var/lib/postgresql and migrate existing data. Redis was published with -p 6379:6379 on all interfaces; remove the published port, attach Redis to an internal network shared only with the API, and require authentication anyway. Review the other services for published ports and bind any that must stay to 127.0.0.1.
Related pages
Section titled “Related pages”- Docker section start
- Docker images, containers and registries: the writable container layer and why it is disposable.
- Docker Compose and environment variables: volumes and networks in a full stack.
- Kubernetes networking: the cluster-scale equivalent of these ideas.