Docker is a popular containerization technology, but sometimes you encounter strange problems when building images. One of the common problems is a "go.mod file not found" error message during the build process, even though the file obviously exists. This issue can be confusing, but there are actually several possible causes and solutions. In this article, we will explore this problem and provide you with some solutions. PHP editor Baicao will help you understand and solve this problem so that your Docker build goes smoothly.
I'm trying to make a full stack application using go backend and nextjs frontend (which I haven't created yet). I'm following the tutorial for making the backend and so far everything is working fine. However, I want to move the backend stuff into its own folder so I can keep it separate from the frontend. Now whenever I run docker compose build
it completes without a hitch, but when I run docker compose up
this is what I get (I am using air for thermal Overload function):
goapp-1 | watching . goapp-1 | watching backend goapp-1 | watching backend/cmd goapp-1 | watching backend/cmd/database goapp-1 | watching backend/cmd/handlers goapp-1 | watching backend/cmd/models goapp-1 | watching backend/tmp goapp-1 | !exclude tmp goapp-1 | building... goapp-1 | go: go.mod file not found in current directory or any parent directory; see 'go help modules' goapp-1 | failed to build, error: exit status 1
But when I go into Docker Desktop and run ls
in that image, it says go.mod
is there!
So where is the problem?
I tried changing the target directory and context in both compose.yaml
and my dockerfile, without success. Running go build
instead of air
also gives me the same error.
This is my file tree:
databeis2 ┣ .vscode ┃ ┗ settings.json ┣ backend ┃ ┣ cmd ┃ ┃ ┣ ... ┃ ┃ ┣ main.go ┃ ┃ ┗ routes.go ┃ ┣ tmp ┃ ┃ ┣ build-errors.log ┃ ┃ ┗ main ┃ ┣ .air.toml ┃ ┣ Dockerfile ┃ ┣ go.mod ┃ ┣ go.sum ┃ ┗ pre_cmd.txt ┣ tmp ┃ ┗ build-errors.log ┣ .env ┗ compose.yaml
My docker file:
FROM golang:1.21 WORKDIR /app RUN go install github.com/cosmtrek/air@latest COPY . . RUN go mod tidy
and compose.yaml:
<code>services: goapp: build: context: ./backend env_file: - .env ports: - 8000:8000 volumes: - .:/app command: air ./cmd/main.go -b 0.0.0.0 depends_on: - db db: image: postgres:alpine environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} ports: - 5432:5432 volumes: - postgres-db:/var/lib/postgresql/data volumes: postgres-db: </code>
Any help would be greatly appreciated! !
I solved it! The problem is that after copying the files in the dockerfile, I need to change WORKDIR
to backend
.
FROM golang:1.21 WORKDIR /app RUN go install github.com/cosmtrek/air@latest COPY . . # Add the below line WORKDIR /app/backend RUN go mod tidy
The above is the detailed content of Docker: 'go.mod file not found' when it obviously exists. For more information, please follow other related articles on the PHP Chinese website!