docker_practice/image/multistage-builds/README.md

192 lines
4.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#
##
Docker 17.05 Docker
### Dockerfile
`Dockerfile`
*
*
`app.go` `Hello World!`
```go
package main
import "fmt"
func main(){
fmt.Printf("Hello World!");
}
```
`Dockerfile.one`
```docker
FROM golang:alpine
RUN apk --no-cache add git ca-certificates
WORKDIR /go/src/github.com/go/helloworld/
COPY app.go .
RUN go get -d -v github.com/go-sql-driver/mysql \
&& CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app . \
&& cp /go/src/github.com/go/helloworld/app /root
WORKDIR /root/
CMD ["./app"]
```
```bash
$ docker build -t go/helloworld:1 -f Dockerfile.one .
```
### Dockerfile
`Dockerfile` `Dockerfile`
`Dockerfile.build`
```docker
FROM golang:alpine
RUN apk --no-cache add git
WORKDIR /go/src/github.com/go/helloworld
COPY app.go .
RUN go get -d -v github.com/go-sql-driver/mysql \
&& CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
```
`Dockerfile.copy`
```docker
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY app .
CMD ["./app"]
```
`build.sh`
```bash
#!/bin/sh
echo Building go/helloworld:build
docker build -t go/helloworld:build . -f Dockerfile.build
docker create --name extract go/helloworld:build
docker cp extract:/go/src/github.com/go/helloworld/app ./app
docker rm -f extract
echo Building go/helloworld:2
docker build --no-cache -t go/helloworld:2 . -f Dockerfile.copy
rm ./app
```
```bash
$ chmod +x build.sh
$ ./build.sh
```
```bash
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
go/helloworld 2 f7cf3465432c 22 seconds ago 6.47MB
go/helloworld 1 f55d3e16affc 2 minutes ago 295MB
```
## 使
Docker v17.05 (`multistage builds`)使 `Dockerfile`
`Dockerfile`
```docker
FROM golang:alpine as builder
RUN apk --no-cache add git
WORKDIR /go/src/github.com/go/helloworld/
RUN go get -d -v github.com/go-sql-driver/mysql
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest as prod
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/github.com/go/helloworld/app .
CMD ["./app"]
```
```bash
$ docker build -t go/helloworld:3 .
```
```bash
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
go/helloworld 3 d6911ed9c846 7 seconds ago 6.47MB
go/helloworld 2 f7cf3465432c 22 seconds ago 6.47MB
go/helloworld 1 f55d3e16affc 2 minutes ago 295MB
```
使
###
使 `as`
```docker
FROM golang:alpine as builder
```
`builder` `--target=builder`
```bash
$ docker build --target builder -t username/imagename:tag .
```
###
使 `COPY --from=0 /go/src/github.com/go/helloworld/app .`
```docker
$ COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf
```