docker network — connect containers to each other
Quick Answer
# Create a network
docker network create my-net
# Run containers on the same network
docker run -d --name db --network my-net postgres:16
docker run -d --name app --network my-net -p 3000:3000 my-app
# Containers can now reach each other by name
# app → postgres://db:5432/mydb
Usage
Containers on the default bridge network cannot resolve each other by name. User-defined networks add automatic DNS.
Other causes & fixes
Inspect a network
docker network ls
docker network inspect my-net
Connect a running container to a network
docker network connect my-net existing-container
Docker Compose — automatic networking
Compose creates a default network for each project. Services can reach each other by service name.
# docker-compose.yml
services:
db:
image: postgres:16
app:
image: my-app
environment:
DATABASE_URL: postgres://db:5432/mydb
# No explicit network needed — Compose handles it
Expose a port to the host
# -p HOST_PORT:CONTAINER_PORT
docker run -p 8080:3000 my-app
# Access at http://localhost:8080
Related