Containers are disposable — data isn't
Containers are meant to be thrown away and replaced. So two questions: how does the API find the database container, and where does the database keep its data when the container is replaced? Answers: a user-defined network gives containers DNS names, and a volume stores data outside the container.
Networks and volumes in action
docker run -d --name api1 cafe-api docker run --rm alpine wget -qO- http://api1:3000/health docker network create cafe-net docker run -d --name api --network cafe-net cafe-api docker run --rm --network cafe-net alpine wget -qO- http://api:3000/health docker volume create pgdata docker run -d --name db --network cafe-net -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:16-alpine docker exec db psql -U postgres -c "CREATE TABLE orders (id int)" docker rm -f db docker run -d --name db --network cafe-net -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:16-alpine docker logs db docker exec db psql -U postgres -c "\dt"