來源:宜信技術學院
感謝公司提供大量機器資源及時間讓我們可以實踐,感謝在此專題上不斷實踐的部分項目及人員的支持。
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"]