Back
5/5

Networks & Ports

+20 XP on completion

#Networks & Ports

After this lesson you'll know:

  • how containers communicate with each other
  • what port mapping means
  • how to create custom networks

#Container Communication

Containers are isolated by default. To talk to each other, they need networks.

# Default networks
docker network ls
# bridge, host, none

#Port Mapping

# Host:Port โ†’ Container:Port
docker run -p 8080:80 nginx
# Visit http://localhost:8080

# Multiple ports
docker run -p 8080:80 -p 443:443 nginx

#Custom Networks

The cleanest approach: create your own network where containers find each other by name.

# Create a network
docker network create my-net

# Start containers in the network
docker run -d --name web --network my-net nginx
docker run -it --network my-net alpine sh

# Now you can reach the web container simply as "web"
/ # ping web

#Important Commands

docker network ls                      # All networks
docker network inspect bridge           # Network details
docker network connect my-net web       # Connect a container later
docker network disconnect my-net web    # Disconnect

#โœ‹ Try it out

  • Create a network testnet, start an Alpine container in it, install curl, start Nginx in the same network as web and curl http://web from the Alpine container
  • docker run -d --name api -p 4000:80 nginx โ€” which port on the host? (4000), which port in the container? (80)

#๐Ÿ“Œ Summary

  • Containers in the same network find each other by name
  • Port mapping: -p HOST_PORT:CONTAINER_PORT
  • docker network create for custom networks
Docker Basics Final

Test your knowledge with a quick quiz!

7 questions ยท +65 XP

โ† โ†’ to navigate