I'm trying to get a golang program that runs on the cmd line to run in a docker container, but importing archive/tar causes errors.
This works:
package main
import (
"fmt"
)
func main() {
fmt.Println("success!")
}
producing the output:
liam gotest $ docker run -it gotest success!
This does not:
package main
import (
"archive/tar"
"fmt"
)
var _ = tar.TypeReg
func main() {
fmt.Println("success!")
}
producing the output:
liam gotest $ docker run -it gotest
standard_init_linux.go:207: exec user process caused "no such file or directory"
This is my Dockerfile:
FROM scratch
WORKDIR /app
COPY . /app
CMD ["./test"]
I'm running:
go version go1.11.4 linux/amd64 Docker version 18.09.1, build 4c52b90 ubuntu 18.04LTS
I'd appreciate any suggestions.
Solved by vishnu narayanan:
I used
`CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo test.go`
to build a static executable, and it worked.
Why ?
This is because of the default go build
behavior. The compiled binary is still looking for libraries in the system path due to dynamic linking.
Since scratch
is empty, the binary is not able to find the system libraries and throws an error.
How to solve this ?
Modify the build script to produce a static compiled build with all libraries built in.
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
Use the output binary from above build for the docker container.