docker 运行 go语言二进制程序 - Go语言中文社区

docker 运行 go语言二进制程序


1、创件dockerfile文件命名为“Dockerfile.scratch"

# 使用scratch开启
FROM scratch
# 拷贝编译程序
COPY main main
# 打开8080端口
EXPOSE 8080
# 运行!
CMD ["./main"]

2、使用go程序编写一个web服务

package main

import (
"fmt"
"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "hello world!")
}

func main() {
        http.HandleFunc("/", handler)
        fmt.Println("服务端口: 8080")
        http.ListenAndServe(":8080", nil)
}

3、编译程序、创建镜像、运行服务

$ go build main.go
$ sudo docker build -t webserver -f Dockerfile.scratch .
$ sudo docker run webserver
standard_init_linux.go:190: exec user process caused "no such file or directory"

运行程序会报以上错误,原因是cgo需要libc库,使用以下命令重新编译运行:

$ CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
$ sudo docker build -t webserver -f Dockerfile.scratch .
$ sudo docker run -p 8080:8080 webserver
服务端口: 8080

成功开启docker容器的 go web服务

转载于:https://my.oschina.net/zhizhisoft/blog/2966531

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_33713503/article/details/92541818
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-02-24 22:15:41
  • 阅读 ( 1715 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢