如何构建含本地Go包的Docker镜像?解决导入路径未含主机名错误
Let's break down what's causing this error and fix it step by step:
Root Cause
The error package docker_test/mult: unrecognized import path "docker_test/mult" pops up because your Go code's import path doesn't align with the directory structure inside the Docker container's GOPATH.
In the golang:1.9.1 image, the default GOPATH is /go, so Go expects packages to live under /go/src/[import-path]. Your Dockerfile copies the mult package to /go/src/app, but your main.go is trying to import it as docker_test/mult—a path that doesn't exist in the container's GOPATH.
Step 1: Fix the Import in main.go
Open your main.go file and update the import line from:
import "docker_test/mult"
To:
import "app"
This matches the exact path where you're placing the mult package inside the container (/go/src/app).
Step 2: Correct the Dockerfile
Your Dockerfile has a critical path mistake in the WORKDIR directive, plus we'll confirm the copy logic is solid. Here's the revised version:
FROM golang:1.9.1 # Copy the mult package to the proper GOPATH location COPY ./docker_test/mult /go/src/app # Set working directory to the app package path (full absolute path required!) WORKDIR /go/src/app # Copy main.go into the working directory COPY ./docker_test/main.go . # Download external dependencies (safe to keep even for local packages) RUN go get -d -v ./... # Compile and install the app binary RUN go install -v ./... # Define runtime command and entrypoint CMD ["app"] ENTRYPOINT ["app", "-f=7", "-s=9"]
Key Fixes:
- WORKDIR Path: Changed
WORKDIR go/src/apptoWORKDIR /go/src/app—without the leading/, Docker would create the directory relative to the base image's root, leading to an invalidGOPATHstructure. - Import Alignment: The copy logic ensures the
multpackage lives at/go/src/app, so the updated import pathappinmain.goworks as expected.
Step 3: Verify Local Directory Structure
Double-check your local project structure matches what the Dockerfile expects. From your /gowork/src directory, it should look like this:
/gowork/src/ ├── Dockerfile └── docker_test/ ├── main.go └── mult/ └── [your mult package files, e.g., mult.go]
Now run docker build -t test_1 . again—it should build successfully!
内容的提问来源于stack exchange,提问作者Mzia

