Dockerfile 构建参数

使用 Docker 做服务部署的时候,经常需要在构建的时候区分环境,让程序能够拿到环境变量,或者让程序能够针对不同环境做出不同的处理。

之前的写法比较原始,在本地打包 Docker 镜像后 push 到服务器,所以就可以在打包的时候修改环境变量的值。虽然只用到了一个区分开发,生产的变量,但是每次都这么做还是比较烦。

最近重新整理 Dockerfile , 又看了下文档,发现可以在 docker build 阶段传入参数的。

如下所示:

FROM golang

ARG app_env

ENV APP_ENV $app_env

...

build 时,可以这样写

docker build -t app -f Dockerfile . --build-arg app_env=dev

这样就可以在 go 程序里 通过 os.Getenv(“APP_ENV”) 拿到环境变量信息,进行不同处理了。

参考资料:

ARG 构建参数

Golang and Docker for development and production