Docker编译结果引入运行容器

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

一、镜像构建

go应用测试代码:

package main

import (
        "fmt"
        "log"
        "net/http"
        "os"
)

func main() {
        // register hello function to handle all requests
        mux := http.NewServeMux()
        mux.HandleFunc("/", hello)

        // use PORT environment variable, or default to 8080
        port := os.Getenv("PORT")
        if port == "" {
                port = "8080"
        }

        // start the web server on port and accept requests
        log.Printf("Server listening on port %s", port)
        log.Fatal(http.ListenAndServe(":"+port, mux))
}

// hello responds to the request with a plain-text "Hello, world" message.
func hello(w http.ResponseWriter, r *http.Request) {
        log.Printf("Serving request: %s", r.URL.Path)
        host, _ := os.Hostname()
        fmt.Fprintf(w, "Hello, world!\n")
        fmt.Fprintf(w, "Version: 1.0.0\n")
        fmt.Fprintf(w, "Hostname: %s\n", host)
}

Dockerfile文件内容:

FROM golang:1.8-alpine
ADD . /go/src/hello-app
RUN go install hello-app

FROM alpine:latest
COPY --from=0 /go/bin/hello-app .
ENV PORT 8080
CMD ["./hello-app"]

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

二、编译运行

[root@test11-41044 hello-app]# docker build -t hello:v1 .
[root@test11-41044 hello-app]# docker run -it -d hello:v1
c9a54fd4d9e7c0b8d4d50ad17a36296d768d8392ec8257b250abc381662b10f1

[root@test11-41044 hello-app]# curl 169.254.30.2:8080
Hello, world!
Version: 1.0.0
Hostname: c9a54fd4d9e7

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注