26

golang 之精简镜像完备篇

 4 years ago
source link: https://www.tuicool.com/articles/ZJ3iIvR
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

引用

golang 镜像很大,因为要开发golang的应用,所以在编写dockerfile的时候

FROM golang:1.13-stretch
docker images 
golang                                                 1.13-stretch                       d68f79d0e22c        7 weeks ago         763MB

可以看到这个官方的镜像大概有7百多M。而我们的程序只需要运行的环境即可,因此对镜像的大小需要精简一下,以免浪费空间。

下面开始精简镜像

alpine

刚开始也是考虑apline .但是对C的支持不太好。

  • 在docker的alpine镜像上运行cgo项目会出现问题,提示panic: standard_init_linux.go:175: exec user process caused "no such file or directory"问题。
    原因是当cgo开启时,默认是按照动态库的方式来链接so文件的,但alpine只支持静态链接,所以会出错。
  • 通过设置CGO_ENABLED=0来解决,此时cgo也不可用了。此法不行
    调用go build --ldflags "-extldflags -static" ,来让gcc使用静态编译可以解决问题。
    或者采用更大的Linux镜像,比如Ubuntu也可以解决。

ubuntu

FROM ubuntu
ubuntu                                                 latest                             775349758637        2 days ago          64.2MB

可以看到也只有64.2M

dockerfile 采取多层构建方式

  • FROM golang:1.13-stretch
    用对go功能比较齐全镜像编译源程序,生成可执行文件
  • FROM ubuntu
    用精简镜像作为最终的容器的镜像
  • 拷贝可执行文件到容器内
  • 打包生成最终的镜像
FROM golang:1.13-stretch

#docker中GOPATH为 '/go'

# Copy all project and build it
# This layer will be rebuilt when ever a file has changed in the project directory
# 拷贝源代码到docker指定项目和路径中

ENV ROOT_PATH /go/src/xxx

COPY . $ROOT_PATH/xx

##设置run命令执行的路径,如果我只编译某个目录的
WORKDIR $ROOT_PATH/xx/cmd/
RUN go build -o /bin/xx


## This results in a single layer image
FROM ubuntu
COPY --from=build /bin/xx /xx
COPY config.json docker-entrypoint.sh /app/

COPY cmd/application.toml /app/cmd/


WORKDIR /app/
RUN chmod 777 docker-entrypoint.sh
EXPOSE 8080
#
ENTRYPOINT ["./docker-entrypoint.sh"]
CMD ["release"]

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK