Container Networking
By default, a container works alone. It cannot see or talk to any other container, even one running on the same computer. This page shows how to connect two containers so they can talk to each other by name.
The Problem
Each container is isolated by default. Two separate containers do not automatically know about each other, even if both are running on your machine at the same time.
You could find a container’s internal IP address and use that instead. But an IP address changes every time a container restarts. Hardcoding one is fragile, and it breaks easily.
The Fix: A User-Defined Network
Docker lets you create your own network and attach containers to it. Containers on the same user-defined network can reach each other by container name — Docker handles the name-to-address lookup for you.
All commands on this page are folder-independent. You can run them from anywhere on your computer.
Create a network
docker network create my-networkRun nginx on it
docker run -d --network my-network --name web nginxRun your Next.js container on the same network
docker run -d --network my-network --name next-app -p 3000:3000 my-next-appProve they can see each other
Open a shell inside your Next.js container:
docker exec -it next-app shFrom inside that shell, reach the nginx container by name:
wget -qO- http://webThis returns nginx’s welcome page HTML — sent from one container to another, using the name web, not an IP address. Type exit to leave the shell.
This only works because both containers were started with --network my-network. Containers on Docker’s default network cannot look each other up by name this way — only user-defined networks like this one support it.
Why This Matters Soon
A later section adds an Express API and a PostgreSQL database to this same app. Your Next.js app will need to reach the API. The API will need to reach the database. Both will use container names, exactly like next-app just reached web.
Once you reach Docker Compose in a later section, this network creation happens automatically — Compose builds a shared network for every service in your project without you typing docker network create yourself. Understanding the manual version now is what makes Compose’s behavior make sense later, instead of feeling like magic.
Hands-on Task
- Create a network and attach both an
nginxcontainer and yourmy-next-appcontainer to it. - From inside the Next.js container, use
wgetorcurlto reach nginx by its container name. - Remove the network with
docker network rm my-network— first stop and remove both containers, since a network in use cannot be deleted.
Quick Check
- Can you explain why hardcoding a container’s IP address is fragile?
- Do you understand why
webresolved to nginx’s container, and not an IP address? - Can you explain why this would not have worked without
--network my-network?
Next → Environment Variables