Search code examples
dockerdocker-composedocker-network

how to use networking when building docker-compose?


i want to build a docker image of my app. the build process (tests) requires other services (db). seems like my app can't connect to the db

i managed to replicate the problem using simple and small images.

dockerfile (it just tries to reach web endpoint)

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

docker-compose

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

during docker-compose up i got

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

how can i access other container during build process?


Solution

  • you need to use network as host in your compose:

    build:
         network: host
    

    and access it using localhost:port

    Example:

    docker-compose:

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

    Dockerfile:

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

    run web:

    docker-compose up -d --build web
    

    run app:

    docker-compose up -d --build app
    

    output:

    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