Home >Backend Development >Golang >Why Does My Dockerized Go Web App Fail with a 'no such file or directory' Error?

Why Does My Dockerized Go Web App Fail with a 'no such file or directory' Error?

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 19:53:13905browse

Why Does My Dockerized Go Web App Fail with a

Error in Executing User Process in Docker with Go Web App

Issue

When running a Dockerized Go web application, an error is encountered indicating "no such file or directory" in standard_init_linux.go:190.

Go Code

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)

}

Docker File

FROM scratch
WORKDIR /home/ubuntu/go
COPY webapp /
EXPOSE 8080
CMD ["/webapp"]

Cause and Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn