登录
首页 >  Golang >  Go教程

GolangDocker环境搭建教程详解

时间:2025-10-25 11:09:52 354浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Golang Docker开发环境搭建教程》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

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

如何使用Golang在Docker中搭建开发环境

用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 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 = 1000 exclude_dir = ["assets", "tmp", "vendor"] exclude_file = [] exclude_regex = ["_test\.go"] exclude_unchanged = false follow_symlink = false include_ext = ["go", "tpl", "tmpl", "html"] kill_delay = "0s" log = "build-errors.log" poll = false poll_interval = 0 post_cmd = "" pre_cmd = "" rerun = false rerun_delay = 500 send_interrupt = false stop_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 带来的环境一致性。

理论要掌握,实操不能落!以上关于《GolangDocker环境搭建教程详解》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>