Docker | 构建镜像
1. 修改已有镜像
在ubuntu:22.04中添加Git
docker run -it --name example ubuntu:22.04 bash
## example容器内下面命令安装git
apt-get update
apt-get install git
# 构建新镜像
docker container commit example ubuntu-git:22.04
2. Dockerfile构建
在ubuntu:22.04中添加Git
Dockerfile
FROM ubuntu:22.04
RUN apt-get update
RUN apt-get install git -y
ENTRYPOINT bash
# 构建镜像
docker build -t ubuntu-git:22.04 -f Dockerfile .
3. Dockerfile多段构建
编译Go server
3.1. 文件树
hello-go
├── Dockerfile
├── go.mod
└── main.go
Dockerfile
# 编译源码
FROM golang:1.16 as builder
# 项目文件夹名
ARG project=hello-go
WORKDIR /go
RUN mkdir $project
COPY * $project/
WORKDIR $project
# 配置镜像源
RUN go env -w GOPROXY=https://goproxy.cn
# 接取依赖
RUN go mod vendor
# 编译程序
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -v -o /go/main
# 打包镜像
FROM alpine:3.15 as runtime
COPY --from=builder /go/main /main
RUN chmod +x /main
WORKDIR /
ENTRYPOINT ./main
main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})
r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}
go.mod
module hello-go
go 1.17
require github.com/gin-gonic/gin v1.7.7
require (
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/golang/protobuf v1.3.3 // indirect
github.com/json-iterator/go v1.1.9 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
)
3.2. 构建与测试
构建镜像
# hello-go文件夹内执行
docker build -t http-server:1.0 -f Dockerfile .
启动测试
docker run -it --rm http-server:1.0