For example, suppose your app is in a directory called myapp, and your docker-compose.yml looks like this:
version: "3.8"services:web:build: .ports:- "8000:8000"db:image: postgresports:- "8001:5432"
When you run docker-compose up, the following happens:
A network called myapp_default is created.
A container is created using web’s configuration. It joins the network myapp_default under the name web.
A container is created using db’s configuration. It joins the network myapp_default under the name db.
Each container can now look up the hostname web or db and get back the appropriate container’s IP address. For example, web’s application code could connect to the URL postgres://db:5432 and start using the Postgres database.
具体看视频是,在这个容器内部创建了一个dns服务器,db就对应了dbcontainer网络,并且web服务器可以访问db的网络。
It is important to note the distinction between HOST_PORT and CONTAINER_PORT. In the above example, for db, the HOST_PORT is 8001 and the container port is 5432 (postgres default). Networked service-to-service communication uses the CONTAINER_PORT. When HOST_PORT is defined, the service is accessible outside the swarm as well.
我们需要指出的host_port和container_port之间的区别
container_port是用于 Networked service-to-service communication
host_port可以从宿主机外部访问
Within the web container, your connection string to db would look like postgres://db:5432, and from the host machine, the connection string would look like postgres://{DOCKER_IP}:8001.
