当Go主文件位于嵌套目录时,如何解决Dockerfile与docker-compose的配置问题?
Hey there, let's work through this Docker + Go setup issue step by step. The error no Go files in /app happens because the Air tool is looking for Go code in your working directory (/app), but your main entry point is nested in cmd/appCode. Plus, there was a small mistake in your Dockerfile's copy command that was probably messing up your file structure inside the container.
Here's how to fix it:
1. Fix the Dockerfile's COPY command
Your original COPY ../.. . is incorrect because when you build the Docker image, the build context is your project root directory (where the Dockerfile lives). Changing that to COPY . . will correctly copy all your project files into the /app directory in the container.
2. Tell Air where your main.go is located
Since your main.go isn't in the root /app directory, you need to configure Air to build from the correct path. You have two simple options here:
Option A: Pass build commands directly in the Dockerfile
Update your Dockerfile's CMD to explicitly point Air to your main.go:
FROM golang:1.16 WORKDIR /app COPY go.mod . COPY go.sum . RUN go mod download COPY . . # Fixed copy command RUN curl -sSfL https://raw.githubusercontent.com/cosmtrek/air/master/install.sh | sh -s -- -b $(go env GOPATH)/bin # Command to build and run from cmd/appCode CMD ["air", "-build.cmd", "go build -o ./tmp/main ./cmd/appCode/main.go", "-build.bin", "./tmp/main"]
Option B: Use an Air configuration file
Create a .air.toml file in your project root directory with these settings (this gives you more control over Air's behavior):
root = "." tmp_dir = "tmp" [build] cmd = "go build -o ./tmp/main ./cmd/appCode/main.go" bin = "./tmp/main" exclude_dir = ["assets", "tmp", "vendor", ".git"] include_ext = ["go", "tpl", "tmpl", "html"]
Then update your Dockerfile's CMD to just:
CMD ["air"]
Air will automatically detect the .air.toml file and use its settings.
3. Verify your docker-compose.yml is correct
Your current volume mapping - .:/app is perfect—it mounts your local project files into the container, so Air can pick up code changes instantly. No need to change this part.
4. Test the setup
Run these commands to rebuild and start your services:
docker-compose down && docker-compose up --build
Why your previous attempts didn't work
When you tried setting WORKDIR to /app/cmd/appCode, you broke the Go module setup—since your go.mod is in the project root, Go couldn't find the module file when working from the subdirectory, leading to hidden dependency issues. Keeping WORKDIR at /app (where your go.mod lives) and telling Air where to find the main.go is the right approach.
内容的提问来源于stack exchange,提问作者Patrick Cockrill

