来源:宜信技术学院
感谢公司提供大量机器资源及时间让我们可以实践,感谢在此专题上不断实践的部分项目及人员的支持。
1.2 Docker容器
只要记住以上三点就能写出不错的Dockerfile。
FROM ubuntu:16.04 RUN apt-get update RUN apt-get install -y apt-utils libjpeg-dev python-pip RUN pip install --upgrade pip RUN easy_install -U setuptools RUN apt-get clean
FROM ubuntu:16.04 RUN apt-get update && apt-get install -y apt-utils libjpeg-dev python-pip && pip install --upgrade pip && easy_install -U setuptools && apt-get clean
从下表可以看出两个Dockerfile所编译出来的镜像大小:
$ docker images | grep ubuntu REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu 16.04 9361ce633ff1 1 days ago 422MB ubuntu 16.04-1 3f5b979df1a9 1 days ago 412MB
使用多阶构建
FROM golang:1.11.4-alpine3.8 AS build-env ENV GO111MODULE=off ENV GO15VENDOREXPERIMENT=1 ENV BUILDPATH=http://github.com/lattecake/hello RUN mkdir -p /go/src/${BUILDPATH} COPY ./ /go/src/${BUILDPATH} RUN cd /go/src/${BUILDPATH} && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go install –v CMD [/go/bin/hello]
以Golang为例,它运行时不依赖任何环境,只需要有一个编译环境,那这个编译环境在实际运行时是没有任务作用的,编译完成后,那些源码和编译器已经没有任务用处了也就没必要留在镜像里。
Dockerfile.build
FROM golang:1.11.4-alpine3.8 AS build-env ENV GO111MODULE=off ENV GO15VENDOREXPERIMENT=1 ENV BUILDPATH=http://github.com/lattecake/hello RUN mkdir -p /go/src/${BUILDPATH} COPY ./ /go/src/${BUILDPATH} RUN cd /go/src/${BUILDPATH} && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go install –v
Dockerfile.run
FROM alpine:latest RUN apk –no-cache add ca-certificates WORKDIR /root ADD hello . CMD ["./hello"]
#!/bin/sh docker build -t –rm hello:build . -f Dockerfile.build docker create –name extract hello:build docker cp extract:/go/bin/hello ./hello docker rm -f extract docker build –no-cache -t –rm hello:run . -f Dockerfile.run rm -rf ./hello
FROM golang:1.11.2-alpine3.8 AS build-env
然后从上一阶段的镜像中复制文件,也可以复制任意镜像中的文件:
COPY –from=build-env /go/bin/hello /usr/bin/hello
FROM golang:1.11.4-alpine3.8 AS build-env ENV GO111MODULE=off ENV GO15VENDOREXPERIMENT=1 ENV GITPATH=http://github.com/lattecake/hello RUN mkdir -p /go/src/${GITPATH} COPY ./ /go/src/${GITPATH} RUN cd /go/src/${GITPATH} && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go install -v FROM alpine:latest ENV apk –no-cache add ca-certificates COPY --from=build-env /go/bin/hello /root/hello WORKDIR /root CMD ["/root/hello"]