Data and Networking: Volumes and Ports
Harry
· 14 Sep 2026
· 3 views
Advertisement
Containers are ephemeral
When you remove a container, everything written inside it disappears. That is fine for stateless apps, but a database needs its files to survive restarts. Docker solves this with volumes.
Bind mounts vs named volumes
- A bind mount maps a folder on your host into the container. Great for development – edit code on the host and the container sees it instantly.
- A named volume is storage Docker manages for you. Best for databases and production data.
# Bind mount: host folder -> container folder
docker run -v $(pwd)/site:/usr/share/nginx/html -p 8080:80 nginx
# Named volume for a database
docker volume create pgdata
docker run -d -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres
Now the Postgres data lives in the pgdata volume and survives docker rm of the container.
Publishing ports
Containers are isolated on their own network, so a service is not reachable from the host until you publish its port with -p host:container. The host port is what you type in the browser; the container port is what the app listens on inside.
docker run -d -p 8080:80 nginx # browser 8080 -> container 80
Connecting containers together
Create a user-defined network and containers on it can reach each other by name – Docker runs an internal DNS. This is how an app container talks to its database container:
docker network create appnet
docker run -d --name db --network appnet -e POSTGRES_PASSWORD=secret postgres
docker run -d --name api --network appnet -p 3000:3000 myapp:1.0
# inside 'api', the database host is simply: db
Key points
- Data written inside a container is lost on removal – use volumes to persist it.
- Bind mounts suit development; named volumes suit databases and production.
-p host:containerpublishes a port so the host can reach the service.- Containers on the same user-defined network reach each other by container name.