一、go代码
go
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Docker!")
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server running on http://127.0.0.1:8080")
http.ListenAndServe(":8080", nil)
}
二、Dockerfile文件
bash
# 使用官方 Go 镜像作为构建环境
FROM golang:1.25.5 AS builder
# 设置代理
#ARG HTTP_PROXY=http://192.168.1.163:7890
#ARG HTTPS_PROXY=http://192.168.1.163:7890
#ENV HTTP_PROXY=${HTTP_PROXY}
#ENV HTTPS_PROXY=${HTTPS_PROXY}
# 设置工作目录
WORKDIR /app
# 复制 go.mod 和 go.sum,先下载依赖
#COPY ../go.mod go.sum ./
COPY go.mod ./
RUN go mod download
# 复制项目代码
COPY . .
# 编译 Go 程序,生成可执行文件 app *注意:Go 程序 + Alpine = 必须 CGO_ENABLED=0
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app
# 使用最小镜像运行程序
FROM alpine:3.17
WORKDIR /app
# 复制编译好的可执行文件
COPY --from=builder /app/app .
# 容器启动时执行 app
CMD ["./app"]
# 容器暴露端口
EXPOSE 8080
三、执行命令
创建go项目镜像,镜像名:my_hello_world
bash
docker build -t my_hello_world .
查看镜像列表
bash
docker images
创建项目镜像的容器,并运行,-d后台运行,-p端口[容器:本机]
bash
docker run -d -p 8081:8080 a0fabfbbaf94(镜像id)
查看容器列表
bash
docker ps # 查看在运行的
docker ps # 查看创建的
四、其他命令
bash
docker start 容器id # 开始容器
docker exec -it 容器id /bin/sh # 进入容器
docker stop 容器id # 停止容器
docker rm 容器id # 删除容器
docker rmi 镜像id # 删除镜像