You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

当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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:24:08