使用dockerfile的env或者label指令,在build的时候传递过去。
FROM alpine
ARG GIT_COMMIT=0
ENV GIT_COMMIT=${GIT_COMMIT}
LABEL GIT_COMMIT=${GIT_COMMIT}
docker build --file .\alpine.dockerfile --tag test --build-arg GIT_COMMIT=$(git rev-parse HEAD) .
效果:
$ docker inspect test
[
{
"Id": "sha256:ae0b8e8940df391f35fd9119a981019a0c174b54a51225c9001a8b9536a90ec9",
"RepoTags": [
"test:latest"
],
"RepoDigests": [],
"Parent": "sha256:3b3cda3111fa9895127e271e15c890295102427948d746dbd8148e44e518096f",
"Comment": "",
"Created": "2019-05-12T09:34:12.929395544Z",
"Container": "f27852e7a76275570a3c2e42b365249b85961eabba892cb16636367a108464d0",
"ContainerConfig": {
"Hostname": "f27852e7a762",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GIT_COMMIT=b14fd66b44180a9b8dd2bce98417699424d08fbb"
],
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"LABEL GIT_COMMIT=b14fd66b44180a9b8dd2bce98417699424d08fbb"
],
"ArgsEscaped": true,
"Image": "sha256:3b3cda3111fa9895127e271e15c890295102427948d746dbd8148e44e518096f",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"GIT_COMMIT": "b14fd66b44180a9b8dd2bce98417699424d08fbb"
}
},
"DockerVersion": "18.09.5",
"Author": "",
"Config": {
"Hostname": "",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GIT_COMMIT=b14fd66b44180a9b8dd2bce98417699424d08fbb"
],
"Cmd": [
"/bin/sh"
],
"ArgsEscaped": true,
"Image": "sha256:3b3cda3111fa9895127e271e15c890295102427948d746dbd8148e44e518096f",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {
"GIT_COMMIT": "b14fd66b44180a9b8dd2bce98417699424d08fbb"
}
},
"Architecture": "amd64",
"Os": "linux",
"Size": 5533135,
"VirtualSize": 5533135,
"GraphDriver": {
"Data": {
"MergedDir": "/var/lib/docker/overlay2/e3218e675ce11527bd72025d3a5b65afaf241dd3e4cb1c60babed524235b30df/merged",
"UpperDir": "/var/lib/docker/overlay2/e3218e675ce11527bd72025d3a5b65afaf241dd3e4cb1c60babed524235b30df/diff",
"WorkDir": "/var/lib/docker/overlay2/e3218e675ce11527bd72025d3a5b65afaf241dd3e4cb1c60babed524235b30df/work"
},
"Name": "overlay2"
},
"RootFS": {
"Type": "layers",
"Layers": [
"sha256:f1b5933fe4b5f49bbe8258745cf396afe07e625bdab3168e364daf7c956b6b81"
]
},
"Metadata": {
"LastTagTime": "2019-05-12T09:34:12.97186321Z"
}
}
]
感谢!采用这个方法解决了
Dockerfile 中添加
ARG GIT_COMMIT
ENV GIT_COMMIT=${GIT_COMMIT}
LABEL GIT_COMMIT=${GIT_COMMIT}
生成 docker 镜像的脚本中添加
GIT_COMMIT=$(git rev-parse --short HEAD)
docker build --build-arg GIT_COMMIT=$GIT_COMMIT .
查看 git commit 信息
# docker inspect f6753354f0ec | grep GIT_COMMIT
# docker exec -t f6753354f0ec /bin/bash 'echo $GIT_COMMIT'