简体   繁体   中英

Why does building and image with docker compose fail but succeeds without it?

I am trying to build an image with docker compose and it fails, however it works with just docker. I have read some SO posts saying that the error thrown when failing happens when a file/folder cannot be found in the Dockerfile. The build works when building with docker so I dont know why it wouldn't work with docker-compose. Why is this happening?

The structure for this project is this:

parent_proj
 |_proj
   |_Dockerfile
 |_docker-compose.yml

Here is my docker-compose file:

version: '3.4'
services:
  integrations:
    build:
      context: .
      dockerfile: proj/Dockerfile
      network: host
    image: int
    ports:
      - "5000:5000"

Here is the Dockerfile inside proj/

FROM openjdk:11
USER root
#RUN apt-get bash
ARG JAR_FILE=target/proj-0.0.1-SNAPSHOT.jar
COPY ${JAR_FILE} /app2.jar
ENTRYPOINT ["java","-jar", "/app2.jar"]

When I'm inside the proj folder. I can run

docker build . -t proj

The above succeeds and I can subsequently run the container. However when I am in parent_proj and run docker compose build it fails with the error message

failed to compute cache key: failed to walk /var/lib/docker/tmp/buildkit-mount316454722/target: lstat /var/lib/docker/tmp/buildkit-mount316454722/target: no such file or directory

Why does this happen? How can I build successfully with docker-compose without restructuring the project?

thanks

Your Compose build options and the docker build options you show are different. The successful command is (where -f Dockerfile is the default):

docker build ./proj   -t proj    # -f Dockerfile
#            context:    image:       dockerfile:

But your Compose setup is running

docker build .         -t img     -f proj/Dockerfile
#            context:     image:     dockerfile:

Which one is right? In the Dockerfile, you

COPY target/proj-0.0.1-SNAPSHOT.jar /some/container/path

That target/... source path is always relative to the build-context directory (Compose context: option, the directory parameter to docker build ), even if it looks like an absolute path and even if the Dockerfile is in a different directory. If that target directory is a subdirectory of proj then you need the first form.

There's a shorthand Compose build: syntax if the only thing you need to specify is the context directory, and I'd use that here. If you don't specifically care what the image name is (you're not pushing it to a registry) then Compose can pick a reasonable name on its own; you don't need to specify image: .

version: '3.8'
services:
  integrations:
    build: ./proj
    ports:
      - "5000:5000"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM