When running a Dockerized Go web application, an error is encountered indicating "no such file or directory" in standard_init_linux.go:190.
package main import ( "fmt" "net/http" "os" ) func hostHandler(w http.ResponseWriter, r *http.Request) { name, err := os.Hostname() if err != nil { panic(err) } fmt.Fprintf(w, "<h1>HOSTNAME: %s</h1><br>", name) fmt.Fprintf(w, "<h1>ENVIRONMENT VARS: </h1><br>") fmt.Fprintf(w, "<ul>") for _, evar := range os.Environ() { fmt.Fprintf(w, "<li>%s</li>", evar) } fmt.Fprintf(w, "</ul>") } func rootHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<h1>Awesome site in Go!</h1><br>") fmt.Fprintf(w, "<a href='/host/'>Host info</a><br>") } func main() { http.HandleFunc("/", rootHandler) http.HandleFunc("/host/", hostHandler) http.ListenAndServe(":8080", nil) }
FROM scratch WORKDIR /home/ubuntu/go COPY webapp / EXPOSE 8080 CMD ["/webapp"]
The error arises because the compiled Go binary lacks a dependency on libc, which is brought in dynamically by default when importing net. To rectify this, compile the Go binary with the following flags:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -tags netgo -ldflags '-w' -o mybin *.go
The above is the detailed content of Why Does My Dockerized Go Web App Fail with a 'no such file or directory' Error?. For more information, please follow other related articles on the PHP Chinese website!