I'm trying to make a fullstack app that uses a go backend and a nextjs frontend (which I haven't created yet). I was following a tutorial for making the backend and everything was working fine so far. However, I wanted to move the backend stuff into its own folder so I could keep it and the frontend separate. Now, whenever I run docker compose build
it completes with no errors, but when I run docker compose up
, this is what I get (I'm using air to have hot reload functionality):
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
However, when I go into Docker desktop and run ls
in that image, it shows that go.mod
is right there!
So what's the issue?
I've tried changing the target directories and contexts in compose.yaml
and my dockerfile, all to no success. Running go build
instead of air
gives me the same error as well.
Here's 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 dockerfile:
FROM golang:1.21
WORKDIR /app
RUN go install github.com/cosmtrek/air@latest
COPY . .
RUN go mod tidy
And compose.yaml:
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:
Any help would be massively appreciated!!
I solved it! The issue was I needed to change my WORKDIR
to backend
after copying the files in my dockerfile.
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