先编写Dockerfile和docker-compose.yml实现Go开发环境的容器化,利用air工具实现热重载,通过卷挂载同步代码,启动服务后可实时查看修改效果并自动重启,提升开发效率与环境一致性。

用Golang在Docker中搭建开发环境,核心是利用容器隔离依赖、统一运行时,并提升协作效率。关键在于编写合适的 Dockerfile、配置必要的工具支持开发流程,并通过 docker-compose 简化服务管理。
准备基础的Go项目结构
先创建一个简单的 Go 项目,便于后续构建:
my-go-app/
├── main.go
├── go.mod
└── Dockerfile
示例 main.go:
package main
import “fmt”
func main() {
fmt.Println(“Hello from Go in Docker!”)
}
初始化模块:
立即学习“go语言免费学习笔记(深入)”;
go mod init my-go-app
编写用于开发的Dockerfile
这个 Dockerfile 面向开发,支持热重载和调试:
# 使用官方 Golang 镜像作为基础镜像
FROM golang:1.21-alpine
WORKDIR /app
COPY go.mod .
RUN go mod download
COPY . .
RUN apk add –no-cache git
CMD [“sh”, “-c”, “go run main.go”]
说明:
golang:1.21-alpine:轻量且适合开发go mod download:提前下载依赖,提高后续构建缓存命中率COPY . .:复制源码进容器CMD:默认运行程序
使用docker-compose支持热重载开发
为了实现代码修改后自动重启,可结合 air 工具实现热重载。
安装 air(在容器内):
# 在 Dockerfile 中添加 air 安装步骤RUN go install github.com/cosmtrek/air@latest
创建 .air.toml 配置文件(用于 air):
root = “.”tmp_dir = “tmp”
[build]args_bin = []bin = “tmp/main.bin”delay = 1000exclude_dir = [“assets”, “tmp”, “vendor”]exclude_file = []exclude_regex = [“_test.go”]exclude_unchanged = falsefollow_symlink = falseinclude_ext = [“go”, “tpl”, “tmpl”, “html”]kill_delay = “0s”log = “build-errors.log”poll = falsepoll_interval = 0post_cmd = “”pre_cmd = “”rerun = falsererun_delay = 500send_interrupt = falsestop_on_error = false
[color]app = “”build = “”main = “”runner = “”watcher = “”
[misc]clean_on_exit = false
更新 Dockerfile 的 CMD:
CMD [“air”]
编写 docker-compose.yml:
version: ‘3.8’services: app: build: . ports: – “8080:8080” volumes: – .:/app environment: – GOPATH=/go
这样,宿主机修改代码会实时同步到容器,air 检测到变化自动重启服务。
启动并验证开发环境
运行以下命令启动服务:
docker-compose up –build
看到输出 “Hello from Go in Docker!” 表示成功。修改 main.go 内容,观察容器是否自动重启。
若需进入容器调试:
docker exec -it sh
基本上就这些。这种方式既保持了本地开发的便利性,又享受了 Docker 带来的环境一致性。
以上就是如何使用Golang在Docker中搭建开发环境的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1415581.html
微信扫一扫
支付宝扫一扫