Docker新增了Multi-stage builds功能,其具体执行是把编译和运行分开,这样运行环境就单纯一些,这种比较适合编译后执行的语言,比如golang、java、C等,这种比python语言更适合。

一、镜像构建

go应用测试代码:

 1package main
 2
 3import (
 4        "fmt"
 5        "log"
 6        "net/http"
 7        "os"
 8)
 9
10func main() {
11        // register hello function to handle all requests
12        mux := http.NewServeMux()
13        mux.HandleFunc("/", hello)
14
15        // use PORT environment variable, or default to 8080
16        port := os.Getenv("PORT")
17        if port == "" {
18                port = "8080"
19        }
20
21        // start the web server on port and accept requests
22        log.Printf("Server listening on port %s", port)
23        log.Fatal(http.ListenAndServe(":"+port, mux))
24}
25
26// hello responds to the request with a plain-text "Hello, world" message.
27func hello(w http.ResponseWriter, r *http.Request) {
28        log.Printf("Serving request: %s", r.URL.Path)
29        host, _ := os.Hostname()
30        fmt.Fprintf(w, "Hello, world!\n")
31        fmt.Fprintf(w, "Version: 1.0.0\n")
32        fmt.Fprintf(w, "Hostname: %s\n", host)
33}

Dockerfile文件内容:

1FROM golang:1.8-alpine
2ADD . /go/src/hello-app
3RUN go install hello-app
4
5FROM alpine:latest
6COPY --from=0 /go/bin/hello-app .
7ENV PORT 8080
8CMD ["./hello-app"]

COPY 命令通过指定 –from=0 参数,把前一阶段构建的产物拷贝到了当前的镜像中。

二、编译运行

1[root@test11-41044 hello-app]# docker build -t hello:v1 .
2[root@test11-41044 hello-app]# docker run -it -d hello:v1
3c9a54fd4d9e7c0b8d4d50ad17a36296d768d8392ec8257b250abc381662b10f1
4
5[root@test11-41044 hello-app]# curl 169.254.30.2:8080
6Hello, world!
7Version: 1.0.0
8Hostname: c9a54fd4d9e7