关于 docker 无法使用容器名字进行容器间连接的问题
问题描述
项目名称 : domain-search
原始 endpoint.sh 文件
| #!/bin/sh
echo "Waiting for postgres..."
while ! nc -z domain-search-db 5432; do sleep 0.1 done
echo "PostgreSQL started"
|
原始 docker-compose 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| version: "3.7"
services: domain-search: image: domain-search container_name: domain-search build: context: ./services/domain-search dockerfile: Dockerfile-dev volumes: - "./services/domain-search:/usr/src/app" restart: always ports: - 5013:5000 env_file: - domain-search-dev.env depends_on: - domain-search-db
domain-search-db: image: domain-search-db container_name: domain-search-db build: context: ./services/domain-search/project/db dockerfile: Dockerfile restart: always ports: - 5443:5432 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres
|
以上的文件配置可以使用容器名字进行连接
新版 docker-compose文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| version: "3.7"
services: domain-search: image: domain-search container_name: domain-search build: context: ./services/domain-search dockerfile: Dockerfile-dev volumes: - "./services/domain-search:/usr/src/app" ################# 新增文件挂载 ################# - "/Desktop/workspace/all-domain/domain-search/nameserver.txt:/etc/resolv.conf" ############################################## restart: always ports: - 5013:5000 env_file: - domain-search-dev.env depends_on: - domain-search-db
domain-search-db: image: domain-search-db container_name: domain-search-db build: context: ./services/domain-search/project/db dockerfile: Dockerfile restart: always ports: - 5443:5432 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres
|
挂载文件
1 2 3 4 5 6 7 8 9 10 11
| nameserver 222.88.88.88 nameserver 223.5.5.5 nameserver 223.6.6.6 nameserver 180.76.76.76 nameserver 119.29.29.29 nameserver 208.67.222.222 nameserver 208.67.220.220 nameserver 114.114.114.114 nameserver 1.1.1.1 nameserver 101.226.4.6 nameserver 218.30.118.6
|
当我们挂载进去的文件修改了 docker 容器内部的网络解析功能,就无法用容器名字进行连接,会显示 forward host lookup failed: Unknown host
解决办法
新版 endpoint.sh
1 2 3 4 5 6 7 8 9
| #!/bin/sh
echo "Waiting for postgres..."
while ! nc -z $PG_HOST $PG_PORT; do sleep 0.1 done
echo "PostgreSQL started"
|
直接使用需要连接的容器的 host 及 port 进行连接
最后提示
- 不要随便修改 docker 容器内部的配置
- 对于底层配置的修改记得添加注释