2

#docker 如何从容器A直接访问容器B

 2 years ago
source link: https://xmanyou.com/access-docker-container-by-name-with-network/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
17 August 2021 / docker

#docker 如何从容器A直接访问容器B

测试环境中,我们经常不使用docker-compose,而是直接使用docker run来快速启动一个容器。

当需求启动多个容器,并且相互间需要互相访问时,这种方法就不太方便了。

有没有什么方法呢,可以让两个docker容器可以相互访问,而且不需要使用ip,直接使用容器名呢?

那就是使用network。

处于同一个network下的容器,可以直接使用容器名相互访问。

  • 1). 创建network
docker network create <网络名>
  • 2). 启动容器并加入对应的network
docker run --net <网络名> --name <容器名> <镜像名>

这样就可以了。

不同docker compose中的service如何连接?

同样是network

docker-compose v3.5以后,可以很方便地为network命名,然后在不同compose中使用相同的network,可以将不同文件中的service连接到一起。

# 定义
networks: 
  share-network:
    name: "share-network01"

# 在service中指定
services:
  service1:
    image: <image>
    networks: 
      - share-network

更多docker network命令,可以参考

https://docs.docker.com/engine/reference/commandline/network/

查询已经存在的network

docker network ls

阿斌

Read more posts by this author.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK