当我们mysql在其他容器中运行时,go程序使用docker build生成镜像或者运行的时候,回出现connect refused的报错。因为当时在本地go run的时候config中我们用了127.0.0.1:3306,运行镜像文件的时候就不行。
此时我们需要用到【关联其他容器】的操作,具体实现就是把config中mysql的配置host改成容器名,例如mysql1990.
具体步骤:
一、编写dockerfile
FROM golang:alpine AS builder
# 为我们的镜像设置必要的环境变量
ENV GO111MODULE=on \
GOPROXY=https://goproxy.cn,direct \
CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64
# 移动到工作目录:/build
WORKDIR /build
# 将代码复制到容器中
COPY . .
# 下载依赖信息
RUN go mod download
# 将我们的代码编译成二进制可执行文件 bubble
RUN go build -o bluebell_app .
###################
# 接下来创建一个小镜像
###################
FROM scratch
# 从builder镜像中把静态文件拷贝到当前目录
COPY ./templates /templates
COPY ./static /static
# 从builder镜像中把配置文件拷贝到当前目录
COPY ./conf /conf
# 从builder镜像中把/dist/app 拷贝到当前目录
COPY --from=builder /build/bluebell_app /
# 需要运行的命令
ENTRYPOINT ["/bluebell_app", "/conf/config.ini"]
这里用到【分阶段构建】以及【附带其他文件】的应用。
二、修改config中mysql配置
[mysql]
user = root
password = 123456
host = mysql1990
port = 3306
db = bluebell
三、生成程序的镜像文件
docker build . -t bluebell_app
四、运行镜像文件
docker run --link=mysql1990:mysql1990 -p 9000:9000 bluebell_app
这里用到了--link去关联其他容器
运行正常。
输入http://127.0.0.1:9000