Docker | 构建镜像

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yimtcode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值