Skip to content
JackSparrow414
Go back

Using Docker: Network Configuration

Table of contents

Open Table of contents

Article body

Option 1: the default mode, using docker run -it —name containerName image:tag. When creating the container, leave the network unspecified and let Docker assign it.

  1. When a Docker container starts, Docker assigns an IP address by default. Enter containerOne and inspect it: ifconfig->172.17.0.3.
  2. Start another container, containerTwo: ifconfig->172.17.0.2.
  3. The two containers can now ping each other. For example, run ping 172.17.0.3 in containerTwo.
    Drawbacks:
    You need to know every container’s IP address. This is impractical because shutting down and restarting containers can assign new addresses.
    Open another terminal window and run docker network inspect brideg.
    The Containers section of the output lists the two running containers.

Option 2: use links.

  1. Create the first container: docker run -it —name containerOne image:tag.
  2. Create the second container and link it to the first: docker run -it —name containerTwo —link containerOne(the first container’s name):containerOneAliasName(an alias for the first container) image:tag.
  3. In the second container, ping containerOneAliasName succeeds.
    Note: —link can link multiple containers. It is an array-style option that can be specified repeatedly, for example: —link containerOne:containerOneAliasName —link containerThree:containerThreeAliasName.
    Drawbacks:
    If multiple containers need to reach one another, their startup order matters. A container that needs access to N other containers also needs multiple —link options, which is inconvenient.

Option 3: create your own bridge network. This is also an approach recommended by the official documentation.

  1. Create a custom bridge:
docker network create dhb-net
  1. Check that it was created:
docker network ls
  1. Create the first container, os1, and set its network to dhb-net:
docker run -dit --name os1 --network dhb-net standardos:latest
  1. Create the second container, os2, and set its network to dhb-net:
docker run -dit --name os2 --network dhb-net standardos:latest
  1. Check that Containers under dhb-net contains information for both containers:
docker network inspect dhb-net
  1. Enter either container:
docker exec -it os2 /bin/bash
  1. Run ping os1 (the container name). The ping succeeds.
    Advantages:
    You no longer need each container’s specific IP address. As long as every container uses the same dhb-net (the custom bridge) with —network at startup, they can reach one another by containerName.

Share this post:

Previous Post
Distributed Transactions with Seata: Installing Seata Server and Using AT Mode
Next Post
Using Git Rebase

Comments

Questions, corrections, and experiences are welcome. Sign in with GitHub to comment; both language versions share this discussion.

Comments are available on the live site only.