第 13 章 · 开发机环境:Docker、Git 与 Go
本章目标:在 ~/dev-workspace 上配齐 Git、Go、Docker;用 docker compose 启动 MySQL shop_db;验证与 go-database、gin-web、git-collab 的路径与账号约定一致;为 ch14 部署打底。
学时建议:4~5 小时(含 2.5 小时跟练)
前置:linux-shell ch06(apt)、ch12;WSL 或 Ubuntu 虚拟机。
13.1 场景说明:代码有了,缺 MySQL 和 Go
shop-demo 在 Git 里(git-collab),但本机还缺:
| 缺什么 | 后果 |
|---|---|
| Git 身份 | commit 报 author unknown |
| Go | ch14 无法 go build |
| Docker + MySQL | go-database 无法连 shop_db |
本章在一台机器上把开发机配齐,全部落在 ~/dev-workspace(ch01 约定)。
13.2 学完你能
| 能力 | 验收 |
|---|---|
| git config | git commit 不再报身份 |
| go mod | go version + 空模块 init |
| docker | hello-world 成功 |
| compose | MySQL 3306 监听,shop_db 存在 |
| 路径 | compose 文件在 shop-demo/deploy/ |
13.3 跟练:Git(终端与 git-collab 共用底层)
步骤 1
git --version
步骤 2 — 全局身份(与 GitHub 一致更佳)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global --list | grep -E 'user\.|init\.'
你应该看到 刚设的三项。
为什么 工作台 git-collab 弹窗填的是「本仓库/会话」身份;终端 git config --global 是系统级默认值——两处不矛盾,填同一套最省心。
步骤 3 — 在 shop-demo 验证
cd ~/dev-workspace/shop-demo
git status
13.4 跟练:Go 安装与第一个模块
方式 A — apt(快,版本可能旧)
sudo apt update
sudo apt install -y golang-go
go version
方式 B — 官方新版(推荐长期开发,选修)
从 https://go.dev/dl/ 下载 linux amd64 tarball,解压到 /usr/local/go,PATH 加 /usr/local/go/bin(ch06 PATH 一节)。
步骤 — 练习模块
mkdir -p ~/dev-workspace/go-learn
cd ~/dev-workspace/go-learn
go mod init example.com/learn
cat > main.go << 'EOF'
package main
import "fmt"
func main() { fmt.Println("go ok") }
EOF
go run .
期望:输出 go ok。
与后续关系:gin-web / ch14 在 shop-demo 里 go mod init example.com/shop-demo(或团队 module 路径)。
13.5 跟练:Docker 与 docker 组
步骤 1 — 安装
sudo apt install -y docker.io docker-compose-v2 2>/dev/null || sudo apt install -y docker.io
docker --version
docker compose version 2>/dev/null || docker-compose --version
步骤 2 — 当前用户进 docker 组
sudo usermod -aG docker "$USER"
groups
重要:必须 注销 WSL/重新登录 或 newgrp docker 后:
docker run --rm hello-world
你应该看到 Hello from Docker!
若 permission denied:组未生效 → 重新登录后再试。