Build args and labels
- Go course
- Advanced
- Lesson 51/68
- 4 min
Learn to customize the image with ARG and LABEL.
Build args and labels
ARG takes a value from outside at build time; LABEL adds metadata to the image:
ARG VERSION=dev
RUN go build -ldflags "-X main.version=${VERSION}" -o /out/app .
LABEL org.opencontainers.image.version=$VERSION \
org.opencontainers.image.source="https://github.com/ornek/app"Build: docker build --build-arg VERSION=1.4.0 -t app:1.4.0 .
Don't pass secrets with ARG
ARG values can appear in docker history output; they aren't suitable for passwords and tokens. BuildKit's secret mount is used instead:
RUN --mount=type=secret,id=netrc,target=/root/.netrc go mod downloadRuntime secrets are given to the container, not the image, as environment variables or files.
Practice Version and commit
Declare var version = "dev" and var commit = "yok", to be filled with ldflags. A function info() string returns version + " (" + commit + ")"; print the result.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
var (
version = "dev"
commit = "yok"
)
func info() string {
return version + " (" + commit + ")"
}
func main() {
fmt.Println(info())
}Expected output
dev (yok)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between ARG and ENV?
- ENV exists only at build time
- ARG stores secret values
- ARG exists only at build time, ENV also in the running container Correct answer
- There is no difference
Explanation: ARG values don't carry into the runtime environment; settings the program needs while running are given with ENV.
2 Build variable
____ VERSION=dev
RUN go build -ldflags "-X main.version=${VERSION}" .
ARG VERSION=dev
RUN go build -ldflags "-X main.version=${VERSION}" .
Explanation: ARG is a build-time variable that docker build --build-arg can change.
3 Instruction and when
| Term | Meaning |
|---|---|
ARG |
Build time |
ENV |
Run time |
LABEL |
Image metadata |
--mount=type=secret |
Secret build data |