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

如何构建含本地Go包的Docker镜像?解决导入路径未含主机名错误

Fixing the "unrecognized import path" Error in Docker Go Build

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/app to WORKDIR /go/src/app—without the leading /, Docker would create the directory relative to the base image's root, leading to an invalid GOPATH structure.
  • Import Alignment: The copy logic ensures the mult package lives at /go/src/app, so the updated import path app in main.go works 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:55:57