简体   繁体   中英

docker-compose networking and publishing ports

I'm trying to better understand docker networking, but I'm confused by the following:

I spin up 2 contains via docker-compose (client, api). When I do this, a new network is created, myapp_default , and each container joins this network. The network is a bridge network, and it's at 172.18.0.1 . The client is at 172.18.0.2 and the api is at 172.18.0.3 .

I can now access the client at 172.18.0.2:8080 and the api at 172.18.0.3:3000 -- this makes total sense. I'm confused when I publish ports in docker-compose: 8080:8080 on the client, and 3000:3000 on the api.

Now I can access the containers from:

  • Client at 172.18.0.1:8080 , 172.18.0.2:8080 , and on the docker0 network at 172.17.0.1:8080
  • API at 172.18.0.1:3000 , 172.18.0.3:8080 , and on the docker0 network at 172.17.0.1:3000

1) Why can I access the client and api via the docker0 network when I publish ports?

2) Why can I connect to containers via 172.17.0.1 and 172.18.0.1 at all?

You can only access the container-private IP addresses because you're on the same native-Linux host as the Docker daemon. This doesn't work in any other environment (different hosts, MacOS or Windows hosts, environments like Docker Toolbox where Docker is in a VM) and even using docker inspect to find these IP addresses usually isn't a best practice.

When you publish ports they are accessible on the host at those ports. This does work in every environment (in Docker Toolbox "the host" is the VM) and is the recommended way to access your containers from outside Docker space. Unless you bind to a specific address, the containers are accessible on every host interface and every host IP address; that includes the artificial 172.17.0.1 etc. that get created with Docker bridge networks.

Publishing ports is in addition to the other networking-related setup Docker does; it doesn't prevent you from reaching the containers by other paths.

If you haven't yet, you should also read Networking in Compose in the Docker documentation. Whether you publish ports or not, you can use the names in the docker-compose.yml file like client and api as host names, connecting the the (unmapped) port the actual server processes are listening on. Between this functionality and what you get from publishing ports you don't ever actually need to directly know the container-private IP addresses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM