#!/bin/bash
#
# Run this shell script after you have run the command: "buildah unshare"
#
git clone https://github.com/bryonbaker/resttest.git
cd resttest
go build restest.go
container=$(buildah from scratch)
mnt=$(buildah mount $container)
mkdir $mnt/bin
mkdir $mnt/lib64
buildah config --workingdir /bin $container
buildah copy $container restest /bin/restest
buildah copy $container /lib64/libpthread.so.0 /lib64
buildah copy $container /lib64/libc.so.6 /lib64
buildah copy $container /lib64/ld-linux-x86-64.so.2 /lib64
buildah config --port 8000 $container
#
# This step is not working properly.
# Need to run with podman -p 8000:8000 --entrypoint /bin/restest restest:latest
buildah config --entrypoint /bin/restest $container
buildah commit --format docker $container restest:latest
FROM golang:latest as builder
# The Dockerfile expects the source code of the application
# to reside in ./src/ directory
COPY src /src
WORKDIR /src
# Build statically linked file and strip debug information
# The Dockerfile expects the `main` package to be at the root of the module
RUN CGO_ENABLED=0 go build -ldflags="-extldflags=-static -s -w" -o executable
# scratch is an empty image
FROM scratch
# If you need /bin/sh and a few utilities, uncomment
# the following line. It increases the image by 5.5 MB
# FROM alpine:latest
COPY --from=builder /src/executable /executable
# copy other files if needed
ENTRYPOINT ["/executable"]
Dockerfile要求源代码位于src目录中
<project_root>
|_ Dockerfile
|_ src/
|_ go.mod
|_ package_main.go # file with `package main` and `func main()`
|_ other source files
# Start from the latest Go base image
FROM golang:latest
# Set the Current Working Directory inside the container
WORKDIR /app
# Copy go mod and sum files
COPY go.mod go.sum ./
# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download
3条答案
按热度按时间ftf50wuq1#
@Dave C给出了正确回答这个问题的信息。使用ldd和测试应用程序返回:
因此,对于那些希望使用Buildah构建一个最小容器的人来说,生成它的BASH脚本看起来像这样:
**这会为简单的微服务生成一个14 MB的容器!**没有其他文件需要担心漏洞等。
我有一个小缺陷,我不能在入口点上工作,所以我在开始时覆盖入口点,但要测试它的运行:
然后,只需在终端会话中键入以下内容:
所以感谢戴夫C!
nhn9ugyo2#
我知道这是一个很晚的答案,但它确实告诉了如何为Golang程序构建最瘦的映像。
诀窍是构建静态链接的可执行文件,并将其放入名为
scratch
的空映像中。该映像只包含一个文件,即完全相同的可执行文件。它是最小的映像。Docker文件:
Dockerfile要求源代码位于
src
目录中命令
docker build ./ -t my-minimal-go
生成名为my-minimal-go:latest
的映像为了证明它是最小图像,将其保存到TAR并研究其内容:
内容类似于
并查看图像中的文件列表:
输出量:
只有一个文件,最小的图像。
lg40wkob3#
我假设您已经在Docker映像中包含了应用程序依赖项。
构建docker映像不需要任何外部依赖,只需要Go语言的基础映像就足以在Linux机器上构建和运行。