构建 docker-compose 时如何使用网络?

how to use networking when building docker-compose?

我想构建我的应用程序的 docker 图像。构建过程(测试)需要其他服务(数据库)。好像我的应用无法连接到 db

我设法使用简单的小图像重现了这个问题。

docker文件(它只是试图到达网络端点)

from alpine:3.10.2
run wget web:8080
cmd ["sh"]

docker-撰写

version: "3.7"
services:
  web:
    image: tutum/hello-world
    ports:
      - "8080:80"
  app:
    build: .
    depends_on:
      - web

docker-compose up期间我得到了

wget: bad address 'web:8080'
ERROR: Service 'app' failed to build: The command '/bin/sh -c wget web:8080' returned a non-zero code: 1

如何在构建过程中访问其他容器?

您需要在撰写中使用 network 作为主机:

build:
     network: host

并使用 localhost:port

访问它

示例:

docker-撰写:

version: "3.7"
services:
  web:
    image: tutum/hello-world
    ports:
      - "8080:80"
  app:
    build:
     context: .
     network: host
    depends_on:
      - web

Docker 文件:

FROM alpine:3.10.2
RUN wget localhost:8080
CMD ["sh"]

运行 web:

docker-compose up -d --build web

运行 app:

docker-compose up -d --build app

输出:

Building app
Step 1/3 : FROM alpine:3.10.2
3.10.2: Pulling from library/alpine
9d48c3bd43c5: Pull complete
Digest: sha256:72c42ed48c3a2db31b7dafe17d275b634664a708d901ec9fd57b1529280f01fb
Status: Downloaded newer image for alpine:3.10.2
 ---> 961769676411
Step 2/3 : RUN wget localhost:8080
 ---> Running in f021283ab323
Connecting to localhost:8080 (127.0.0.1:8080)
index.html           100% |********************************|   478  0:00:00 ETA
Removing intermediate container f021283ab323
 ---> aae07c08a119
Step 3/3 : CMD ["sh"]
 ---> Running in e81d9401db71
Removing intermediate container e81d9401db71
 ---> 6c217a535c7d

Successfully built 6c217a535c7d
Successfully tagged docker-test_app:latest
docker-test_web_1 is up-to-date
Creating docker-test_app_1 ... done