|
楼主 |
发表于 2022-7-20 11:22:11
|
显示全部楼层
https://docs.docker.com/compose/networking/
For example, suppose your app is in a directory called myapp, and your docker-compose.yml looks like this:
version: "3.9"
services:
web:
build: .
ports:
- "8000:8000"
db:
image: postgres
ports:
- "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.
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.
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.
如上所示,在3.9版本的 docker compose 中,同一个 docker-compose.yml 中存在2个容器 web 和 db。
1. 会自动创建一个网络,自动命名为 web_db_default
2. 这2个容器会自动加入此默认的网络 web_db_default
3. web 可以通过 "db:8001" 直接访问 db 这个容器的 8001 端口。
当然用 link 直接指定一个网络,让2个容器加入也可以。 |
|